首页 > 解决方案 > 使用asp.net mvc将表对象从视图传递到控制器

问题描述

我是 ASP.net MVC 的新手,仍处于学习阶段:) 谢谢你提前

我创建了视图模型以根据我选择的 PName 填充表数据。

例如:对于 1 个项目,我们有 10 个相关项目,我在屏幕上显示所有行,并对这些行进行一些更新以将其保存回数据库。

我能够获取数据,但是当我尝试将表对象发送到控制器进行保存时,它总是给我 null

Here is my ViewModel

namespace Application.ViewModel.Projects
{
    public class PUpdates
    {
        public List<FItems> items{ get; set; }

    }
}

CSHTML code
@using (Html.BeginForm("PFItems", "Projects", FormMethod.Post))
{
    <table id="test">
        <tr id="testtr">
            <th id="testth"></th>
            <th id="testth"></th>
        </tr>
        @foreach (var item in Model.FItems)
        {
            <tr id="testtr">
                <td id="testtd">
                    @Html.Label(item.Ftype)
                </td>
                <td id="testtd">
                    @Html.TextBox("test", item.AC)
                </td>
            </tr>
        }
        <tr> <td><input type="submit" value="Submit" /></td></tr>

    </table>
}

控制器代码

   [HttpPost]
    public PartialViewResult PFItems(PFUviewmodel)
    {

        return PartialView(viewmodel);
    }

我无法让我的表对象进行更新

标签: asp.net-mvc

解决方案


欢迎来到堆栈溢出 :)

要使模型绑定起作用,您需要在 name 属性中为字段提供索引。看看这个问题,我回答了一个非常相似的问题并进行了解释。

在您的情况下,您需要执行以下操作:

@model Application.ViewModel.Projects.ProjectfinanceUpdate
@using (Html.BeginForm("PartialprojectFinanceItem", "Projects", FormMethod.Post))
{
    <table id="test">
        <tr id="testtr">
            <th id="testth">Financial Type</th>
            <th id="testth">Actual Cost</th>
        </tr>
        @var i =0;
        @foreach (var item in Model.tblFinanceItems)
        {

            <tr id="testtr">
                <td id="testtd">
                    @Html.Label(item.FinancialType)
                </td>
                <td id="testtd">
                    <input name="ProjectfinanceUpdate.tblFinanceItems[@i].ActualCost" value="@item.ActualCost"/>
                </td>
            </tr>
            @i++;
        }
        <tr> <td><input type="submit" value="Submit" /></td></tr>

    </table>
}

重要的部分是模型绑定依赖于 name 属性,因为它是一个列表,所以它需要一个 index 属性。

希望有帮助。


推荐阅读