繁体   English   中英

从Razor视图将模型的子集发布到Controller

[英]Post subset of the Model to the Controller from Razor view

我有一个看起来像这样的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<SupplierInvoiceMatchingDto> ,并且所有表行都是x => x[i].Whatever ,它都会发布所有信息。

我的问题是:如何将列表发布到控制器,同时将模型保持为SupplierInvoiceMatchingVm因为我在此视图中需要模型中的其他东西(为了简洁起见,我已将其取出)。

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

您可以使用[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
}

你的Post动作没有正确地接受模型(应该是你的ViewModel)? 不应该是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM