I have a model class and a viewmodel class on the similar lines as model class (Code is given below) in a MVC application. There is a view whose model is 'viewmodel' and its a form. The corresponding action method for this form submit button has action parameter as viewmodel class. With this scenario mentioned, model binding works fine. Now if i change the data type of the Action method from "viewmodel" to "Model" class , Model binding doest not work accurately and correct data is not received on the server side. Below are the model classes -
public class Model
{
public int A { get; set; }
}
public class ViewModel
{
public Model Model { get; set; }
}
View File code is below :
@model ViewModel
@{
ViewBag.Title = "Test";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm("A", "Customers"))
{
<div class="form-group">
@Html.LabelFor(m => m.Model.A)
@Html.TextBoxFor(m => m.Model.A, new { @class="form-control" })
</div>
<button type="submit" class="btn btn-primary">Save</button>
}
Controller Action Method : With Correct Model Binding behavior -
public ActionResult A(ViewModel model)
{
return Content("Value of A is " + model.Model.A);
}
If i change the action parameter to Model class , model binding behavior doesnot take place. Below is the code -
public ActionResult A(Model model)
{
return Content("Value of A is " + model.A);
}
Why is it so ?
On the browser side , the form data is as - Model.A - 1 Why cant this value bind to Model Class A parameter in the second case metioned ?
nameattributes based onViewModel, notModel, therefore the parameter in the POST method must match (or you can use the[Bind(Prefix="Model")]attribute). As a side note, view models do not contain data models - they contain the properties of your data model that you need in the view - refer What is ViewModel in MVC? - user3559349