【问题标题】:MVC4 model binding with two complex modelsMVC4 模型绑定两个复杂模型
【发布时间】:2013-08-16 08:35:04
【问题描述】:

我的控制器上有一个动作,它采用两个参数,在发布表单时应该捕获这些参数:

[HttpPost]
public ActionResult Index(MyModel model, FormAction action)

想法是模型数据应该在MyModel中捕获,用户按下的按钮应该在FormAction中捕获:

public class MyModel
{
    public string MyValue { get; set; }
}

public class FormAction
{
    public string Command { get; set; }
}

这是我的看法:

@model TestApp.Models.MyModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>

        @using (Html.BeginForm("Index", "Home"))
        {
            @Html.TextBoxFor(x => x.MyValue)

             <input type="submit" value="OK" name="command" />
             <input type="submit" value="Cancel" name="command" />
        }

    </div>
</body>
</html>

如果我向名为“command”的操作添加另一个字符串参数,则按钮的值会通过,但它不会绑定到 FormAction 参数上的 Command 属性 - 该参数始终为空。

如果我将Command 属性添加到MyModel,那么按钮值就会通过。

MVC 模型绑定中是否存在阻止在一个操作方法中绑定多个复杂模型的内容?

【问题讨论】:

    标签: asp.net-mvc model-binding


    【解决方案1】:

    仪表是Html.BeginForm 仅发送来自顶级状态的模型:@model TestApp.Models.MyModel。如果我清楚地了解您要做什么,更好的解决方案是创建 ViewModel:

    public class ViewModel
    {
     public MyModel myModel {get; set;}
    public FormAction formAction {get; set;}
    }
    

    改变视图如下:

    @model TestApp.Models.ViewModel
    
    @{
        Layout = null;
    }
    
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
    </head>
    <body>
        <div>
    
            @using (Html.BeginForm("Index", "Home"))
            {
                @Html.TextBoxFor(model=> model.myModel.MyValue)
                @Html.TextBoxFor(model=> model.formAction.Command)
    
                 <input type="submit" value="OK" name="command" />
                 <input type="submit" value="Cancel" name="command" />
            }
    
        </div>
    </body>
    </html>
    

    并将您的操作更改为:

    [HttpPost]
    public ActionResult Index(ViewModel model)
    

    【讨论】:

    • 我没有对此进行标记,因为前提不正确,但这是我在弄清楚真正问题所在之前最终实施的确切解决方法。
    【解决方案2】:

    我已经深究了这一点,它不起作用的原因仅仅是因为参数被命名为 action。这几乎相当于 MVC 中的关键字,MVC 框架使用它来标识要执行的操作。

    将参数名称更改为其他名称意味着Command 属性按预期通过!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多