MVC模型未传递给控制器 [英] MVC Model not passed to controller
问题描述
我几乎不好意思我无法使它正常工作.我有一个这样的模型:
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; }
}
我有一个剃刀视图,可以正确显示Test1和Test2. Test1的显示如下:
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的显示如下:
Test2 is displayed like this:
@Html.LabelFor(model => model.Test2)
@Html.EditorFor(model => model.Test2)
即我只想显示Test1,但希望用户能够编辑Test2.
i.e. I just want to display Test1, but want the user to be able to edit Test2.
这些在表格内:
@using(Hmtl.BeginForm("Action1", "Controller1", FormMethod.Post)
在Controller1.Action1中,它接收模型:
In Controller1.Action1 it receives the model:
public ActionResult Action1(Test m)
{
}
,但是在这里m.Test1为空,m.Test2已正确填充. m.test1正确显示在视图中.
but in here m.Test1 is null, m.Test2 is correctly populated. m.test1 is correctly displayed in the view.
am confused.com
Am confused.com
预先感谢
雷
推荐答案
模型绑定程序仅看到从HTML表单发布的表单值,这些表单值仅来自表单元素.这不会生成这样的元素:
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
这可能会显示视图绑定的值(真的吗?我从未见过那样做过,也许应该是@Model.Test1
?),但是需要某种HTML表单元素将值发布回服务器. (input
,select
,hidden
等)
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.)
为了有趣,请看一下浏览器中生成的HTML.它们只是带有值的标准表单元素,没有任何东西可以将整个模型存储在任何地方.模型绑定程序只是尝试根据从HTML表单发送的名称/值对来智能地重建模型.
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)
这应该在具有该值的表单中创建一个input type="hidden"
,将值发布到控制器操作时将包括该值.
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.
这篇关于MVC模型未传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!