3
votes

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?

2
Have you tried EditorFor instead of TextBoxFor? - mattytommo
Also, check what's inside Request.Form when debugging the post method - mattytommo
setting to EditorFor gives unhandled NullReferenceException at line 3 when I try to just load the page line =( Type tModel = ViewData.ModelMetadata.ContainerType.GetProperty(ViewData.ModelMetadata.PropertyName).PropertyType;) - dferraro
Open the source view and look for other inputs in the page with id or name "Name" and "Age". Sometimes you accidentally have other inputs with the same name and MVC can't bind because the request create a collection with the values. - Eduardo Molteni
i just checked and there's no duplicate input tags. I really did post all the code, I'm just trying to get a simple example working - dferraro

2 Answers

6
votes

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.

1
votes

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 EditorFors

Try strong typing it:

[HttpGet]
public ActionResult Index()
{
    Person model = new Person {Name = "foo", Age = 44};
    return View(model);
}