Reputation: 6438
Very basic Model:
public class Person
{
public string Name;
public int Age;
}
and 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 push submit button, the person object has all null values for age & name.
Because I used Html.TextBoxFor, shouldn't it have set up all the bindings correctly and the object should have automatically bound back to the POST? It binds just fine in the GET..
Did I miss something in the call to Html.BeginForm() maybe?
Upvotes: 3
Views: 901
Reputation: 39453
You must create Properties in your model
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
instead of
public class Person
{
public string Name;
public int Age;
}
ASP.net MVC only binds properties.
Upvotes: 6
Reputation: 56449
Why is your model an object
in the Get
method? That may be what's confusing the model binder. That also looks like why it throws an exception on page load when you change them to EditorFor
s
Try strong typing it:
[HttpGet]
public ActionResult Index()
{
Person model = new Person {Name = "foo", Age = 44};
return View(model);
}
Upvotes: 1