How to combine two presentation models in razor MVC asp.net

Suppose I have several models as follows:

public class Model1 
{
   public int ID{get;set;}
   public string Name{get;set;}
}

public class Model2 
{
    public int ID{get;set;}
    public string Name{get;set;}
}

class CommonViewModel 
{
    public string Title{get;set;}
    public Model1 model1;
    public Model2 model2;
}

and I have a razor view as follows

@model ProjectName.CommonViewModel

@Html.LabelFor(m => model.Title)           
@Html.EditorFor(m => model.Title)

@Html.LabelFor(m => model.model1.Name)           
@Html.EditorFor(m => model.model1.Name)

on my controller, I have a message that takes a CommonViewModel as a parameter. The general presentation model will matter for Title, but not for model1.Name. Why and how can I get this value, stored and sent back to the post, back to the controller.

+4
source share
2 answers

There CommonViewModelare some problems in your class . It must be public, model1 and model2 must have getter and setter:

public class CommonViewModel
{
    public string Title { get; set; }
    public Model1 model1{get;set;}
    public Model2 model2{get;set;}
}

:

@Html.LabelFor(m => m.Title)           
@Html.EditorFor(m => m.Title)

@Html.LabelFor(m => m.model1.Name)           
@Html.EditorFor(m => m.model1.Name)

.

+4

: POST, GET.

, , POST GET. POST view. , . , :

[HttpPost]
public ViewResult PostActionMethod(CommonViewModel commonViewModel)
{
   if (ModelState.IsValid)
   {
       //your code follows
   }

   return RedirectToAction("GetActionMethod", commonViewModel);
}

[HttpGet]
public ViewResult GetActionMethod(CommonViewModel commonViewModel)
{
   //your code follows

   return View(commonViewModel);
}

, !!!

0

Source: https://habr.com/ru/post/1544539/


All Articles