Reputation: 419
Am almost embarassed that I can't get this to work. I have a model like this:
public class Test
{
public string Test1 {get; set; }
public string Test2 {get; set; }
}
I have a razor view which correctly displays both Test1 and Test2. Test1 is displayed just like this:
@Html.LabelFor(model => mode.Test1)
@Html.Test1
Test2 is displayed like this:
@Html.LabelFor(model => model.Test2)
@Html.EditorFor(model => model.Test2)
i.e. I just want to display Test1, but want the user to be able to edit Test2.
These are within a form:
@using(Hmtl.BeginForm("Action1", "Controller1", FormMethod.Post)
In Controller1.Action1 it receives the model:
public ActionResult Action1(Test m)
{
}
but in here m.Test1 is null, m.Test2 is correctly populated. m.test1 is correctly displayed in the view.
Am confused.com
Thanks in advance,
Ray
Upvotes: 0
Views: 3184
Reputation: 218827
The model binder only sees the form values which are posted from the HTML form, which are only from form elements. This doesn't generate such an element:
@Html.Test1
That may display the value to which the view is bound (does it really? I've never seen it done like that, maybe that should be @Model.Test1
?) but there needs to be an HTML form element of some kind to post a value back to the server. (input
, select
, hidden
, etc.)
For fun, take a look at the HTML generated in the browser. They're just standard form elements with values, there's nothing storing the whole model anywhere. The model binder just tries to intelligently re-construct a model based on the name/value pairs sent from the HTML form.
Try adding a hidden field to the form as well:
@Html.LabelFor(model => model.Test1)
@Model.Test1
@Html.HiddenFor(model => model.Test1)
This should create an input type="hidden"
in the form with that value, which would be included when posting the values to the controller action.
Upvotes: 2