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

dan*_*dan 13 asp.net-mvc jquery entity-framework model-binding razor

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

换句话说,对于一个普通的html元素,例如: <input type="text" />

Hac*_*ese 31

如果您指的是模型绑定,它不需要帮助程序,而是命名约定.助手只是简单易懂地创建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);
     }
}
Run Code Online (Sandbox Code Playgroud)

而这个型号:

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; }
}
Run Code Online (Sandbox Code Playgroud)

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

<form method="POST" action="MyController/Submit">
    <div><label>Some property</label><input type="text" name="SomeProperty" /></div>
    <div><label>Another property</label><input type="text" name="Nested.AnotherProperty" /></div>
    <button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

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

@model MyViewModel
<form method="POST" action="MyController/Submit">
    <div><label>Some property</label><input type="text" name="SomeProperty" value="@Model.SomeProperty" /></div>
    <div><label>Another property</label><input type="text" name="Nested.AnotherProperty" value="@Model.Nested.SomeProperty" /></div>
    <button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

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


Dar*_*rov 7

只要给它一个名字:

<input type="text" name="foo" />
Run Code Online (Sandbox Code Playgroud)

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

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