【问题标题】:Post subset of the Model to the Controller from Razor view从 Razor 视图将模型的子集发布到控制器
【发布时间】:2013-05-29 14:13:32
【问题描述】:

我的 Razor 视图如下所示:

@model Namespace.Namespace.SupplierInvoiceMatchingVm

@using(Html.BeginForm("MatchLines", "PaymentTransaction"))
{
    <table class="dataTable" style="width: 95%; margin: 0px auto;">
    <tr>
        <th></th>
        <th>PO Line</th> 
        <th>Description</th> 
    </tr>
    @for (var i = 0; i < Model.Lines.Count; i++)
    {
        <tr>
            <td>@Html.CheckBoxFor(x => x.Lines[i].Selected)</td>
            <td>@Html.DisplayFor(x =>x.Lines[i].LineRef) @Html.HiddenFor(x => x.Lines[i].LineRef)</td>
            <td>@Html.DisplayFor(x =>x.Lines[i].Description) @Html.HiddenFor(x => x.Lines[i].Description)</td>
        </tr>
    }

    </table>
    <input type="submit" value="Submit"/>
}

其中LinesSupplierInvoiceMatchingDto 对象的列表,MatchLines 方法签名看起来像

public ActionResult MatchLines(IEnumerable<SupplierInvoiceMatchingDto> list)

当我点击这个视图上的提交按钮时,列表以null 的形式传递给控制器​​。

但是,如果我将Model 更改为List&lt;SupplierInvoiceMatchingDto&gt;,并将所有表行更改为x =&gt; x[i].Whatever,它会正常发布所有信息。

我的问题是:我如何让它将列表发布到控制器,同时将模型保持为 SupplierInvoiceMatchingVm,因为我需要在此视图中从模型中获取一些其他内容(为简洁起见,我已将其取出) .

注意:我删除了一些用户输入字段,它不仅仅是发布与给出的相同数据。

【问题讨论】:

    标签: c# asp.net-mvc-3 razor


    【解决方案1】:

    您可以使用[Bind] 属性并指定前缀:

    [HttpPost]
    public ActionResult MatchLines([Bind(Prefix="Lines")] IEnumerable<SupplierInvoiceMatchingDto> list)
    {
        ...
    }
    

    甚至更好地使用视图模型:

    public class MatchLinesViewModel
    {
        public List<SupplierInvoiceMatchingDto> Lines { get; set; }
    }
    

    然后让您的 POST 控制器操作采用此视图模型:

    [HttpPost]
    public ActionResult MatchLines(MatchLinesViewModel model)
    {
        ... model.Lines will obviously contain the required information
    }
    

    【讨论】:

    • 是的,我已经有了带有 Lines 属性的视图模型,我之前只是搞砸了它,需要重新访问它。
    【解决方案2】:

    您的 Post 操作没有正确地纳入模型(应该是您的 ViewModel)?不应该是:

    [HttpPost]
    public ActionResult MatchLines(SupplierInvoiceMatchingVm viewModel)
    {
        var list = viewModel.Lines;
        // ...
    }
    

    【讨论】:

    • 应该,事实证明,我之前尝试过,但它出错了,但我没有给予足够的关注,并认为这是绑定失败。原来它是别的东西,当我修复它时,你的解决方案有效。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多