MVC Model not passed to controller

醉酒当歌 提交于 2019-12-11 19:52:45

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/22488066/mvc-model-not-passed-to-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!