How to combine two view models in razor MVC asp.ne

2019-05-10 14:42发布

问题:

Lets say I have some 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 post back which takes CommonViewModel as a parameter. The common view model will have a value for the Title but not for the model1.Name. Why and how can I get that value stored and sent back in the post back to the controller.

回答1:

Your CommonViewModel class has some issues. It should be public, model1 and model2 should have getter and setter:

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

Also in the view you need to fix:

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

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

The code above works fine in my test.



回答2:

You will need two methods in your controller: One for the POST and the other for the GET.

Since you want to hold onto the values stored in the model, you will have to pass them from the POST method to the GET method. You will also have to specify POST in your view. Here's a round-about idea of how your code needs to be in the controller. I haven't tried this so I'm just going by my gut here:

[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);
}

Hope this helps!!!