user3648646
user3648646

Reputation: 711

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

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.

Upvotes: 3

Views: 7563

Answers (2)

afzalulh
afzalulh

Reputation: 7943

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.

Upvotes: 4

Satwik Nadkarny
Satwik Nadkarny

Reputation: 5135

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!!!

Upvotes: 0

Related Questions