Pass multiple Models from one View to Controller in ASP.Net MVC

Last Reply 6 days ago By dharmendr

Posted 7 days ago

hello,

i have scenerio as follow

1. i have 2 view model viewmodel1 and viewmodel2

2. both has partial view 

3. on my page Index i have submit button which calls Create method

4. on my Create method call i want to get both partial view data how to get it. 

pls advice

public class viewmodel1
{
   public int model1id {get;set;}
}

public class viewmodel2
{
   public int model2id {get;set;}
}

public ActionResult Create(viewmodel1 model1, viewmodel2 model2)
{
    return View();
}
Posted 6 days ago

Hi nauna,

Check this example. Now please take its reference and correct your code.

I have create a common ViewModel that will hold the properties of viewmodel1 and viewmodel2.

Model

viewmodel1

public class viewmodel1
{
    public int model1id { get; set; }
}

viewmodel2

public class viewmodel2
{
    public int model2id { get; set; }
}

ViewModel

public class ViewModel
{
    public viewmodel1 model1 { get; set; }
    public viewmodel2 model2 { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(ViewModel model)
    {
        return View("Index");
    }
}

View

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<_Multiple_ViewModel_MVC.Models.ViewModel>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Index</title>
</head>
<body>
    <div>
        <%using (Html.BeginForm("Create", "Home", FormMethod.Post))
          {%>
        <table>
            <tr>
                <td>Id 1</td>
                <td><%:Html.TextBoxFor(x=>x.model1.model1id) %></td>
            </tr>
            <tr>
                <td>Id 2</td>
                <td><%:Html.TextBoxFor(x => x.model2.model2id)%></td>
            </tr>
        </table>
        <br />
        <input type="submit" value="Create" />
        <%} %>
    </div>
</body>
</html>

Screenshot

The Form

Values in Controller