Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从Razor视图将模型子集发布到控制器_C#_Asp.net Mvc 3_Razor - Fatal编程技术网

C# 从Razor视图将模型子集发布到控制器

C# 从Razor视图将模型子集发布到控制器,c#,asp.net-mvc-3,razor,C#,Asp.net Mvc 3,Razor,我有一个像这样的剃须刀视图: @model Namespace.Namespace.SupplierInvoiceMatchingVm @using(Html.BeginForm("MatchLines", "PaymentTransaction")) { <table class="dataTable" style="width: 95%; margin: 0px auto;"> <tr> <th></th>

我有一个像这样的剃须刀视图:

@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"/>
}
当我点击此视图上的提交按钮时,列表以
null
的形式传递给控制器

但是,如果我将
模型
更改为
列表
,并将所有表行更改为
x=>x[I]。不管是什么
,它都会发布所有信息

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


注意:我去掉了一些用户输入字段,这不仅仅是发布与给定数据相同的数据

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

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

您的Post操作在模型中没有正确执行(应该是您的ViewModel)?难道不是:

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

事实证明,我以前也试过,结果是出错了,但我没有足够的注意,以为是绑定失败了。原来是另外一个问题,当我解决这个问题时,你的解决方案就起作用了。谢谢。是的,我已经有了带有
Lines
属性的视图模型,我之前在传递它时把它搞砸了,需要重新访问它。
public class MatchLinesViewModel
{
    public List<SupplierInvoiceMatchingDto> Lines { get; set; }
}
[HttpPost]
public ActionResult MatchLines(MatchLinesViewModel model)
{
    ... model.Lines will obviously contain the required information
}
[HttpPost]
public ActionResult MatchLines(SupplierInvoiceMatchingVm viewModel)
{
    var list = viewModel.Lines;
    // ...
}