ASP.NET MVC:如何’模型绑定’非html-helper元素

你能告诉我一种方法,我可以将模型属性绑定到一个html元素,不使用html帮助器创建?

换句话说,对于一个普通的html元素,例如:

如果您指的是模型绑定 ,它不需要帮助程序,而是命名约定。 助手只是简单易懂地创建HTML标记。

您可以创建纯HTML输入,只需正确设置name属性即可。 默认命名约定只是基于点,省略父级实体的名称,但从那里对其进行限定。

考虑这个控制器:

 public class MyControllerController : Controller { public ActionResult Submit() { return View(new MyViewModel()); } [HttpPost] public ActionResult Submit(MyViewModel model) { // model should be not null, with properties properly initialized from form values return View(model); } } 

而这个型号:

 public class MyNestedViewModel { public string AnotherProperty { get; set; } } public class MyViewModel { public MyViewModel() { Nested = new MyNestedViewModel(); } public string SomeProperty { get; set; } public MyNestedViewModel Nested { get; set; } } 

您可以纯HTML格式创建以下表单:

 

如果要显示已发布的值(在第二个“ Submit重载中),则必须修改HTML以呈现模型属性。 你将它放在一个视图中,在这种情况下使用Razor语法并调用Submit.cshtml

 @model MyViewModel 

所以,这可以在没有助手的情况下完成,但您希望尽可能多地使用它们。

只要给它一个名字:

  

然后在你的控制器动作中只需要一个具有相同名称的参数:

 public ActionResult Process(string foo) { // The foo argument will contain the value entered in the // corresponding input field }