Controller message does not receive model
A very simple model:
public class Person
{
public string Name;
public int Age;
}
and a very simple view:
@model DynWebPOC.Models.Person
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Hello, @Model.Name
<br/>
You're getting old at @Model.Age years old now!
@using(Html.BeginForm("Index","Test",FormMethod.Post))
{
<fieldset>
<label for="name" style="color: whitesmoke">Name:</label>
@Html.TextBoxFor(m => m.Name)
<br/>
<label for="age" style="color: whitesmoke">Age:</label>
@Html.TextBoxFor(m => m.Age)
<br/>
<input type="submit" value="Submit"/>
</fieldset>
}
And a very simple controller:
public class TestController : Controller
{
[HttpGet]
public ActionResult Index()
{
object model = new Person {Name = "foo", Age = 44};
return View(model);
}
[HttpPost]
public ActionResult Index(Person person)
{
return View();
}
}
When the screen loads, the values bind correctly to the page. But when I click the submit button, the person object has all null values for age and name.
Since I was using Html.TextBoxFor, shouldn't it set all bindings correctly and the object should automatically bind to POST? It binds fine in GET ..
I missed something in the Html.BeginForm () call, maybe?
source to share
Why is your model object
in a method Get
? Perhaps this is a confused model binder. This is also similar to why it throws an exception on page load when you change them to EditorFor
s
Try entering it:
[HttpGet]
public ActionResult Index()
{
Person model = new Person {Name = "foo", Age = 44};
return View(model);
}
source to share