如何为没有主键的多个模型对象创建编辑视图?

时间:2019-06-04 14:41:10

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

我正在服务器端进行一些计算,并在视图中显示表格。我希望能够在单个视图中编辑表格的每一行。

如何将模型绑定到视图,以便在视图中编辑后可以在POST控制器操作中获得模型对象的列表?

我的模特:

    public class Item
    {
        public float floatValue1;
        public string stringValue1;
        public float floatValue2;
        public double doubleValue1;
    }

通过此模型,我创建了一个表视图,该视图列出了HTML表中的值。 但是,在编辑视图中,我不需要编辑每个字段。例如,仅floatValue1stringValue1floatValue2是可编辑的。 doubleValue1应该保持其当前值,并且用户无法对其进行编辑。

我尝试了在网上找到的建议:

我的控制器将Item个对象的列表作为IList<Item>发送到编辑视图 编辑视图具有带有for循环的html表单,每次迭代都使用Html.EditorFor

创建一个表行。
public ActionResult PricingEdit(int? i)
{
     var result = calculations();  // returns IList<Item>
     return View(result.ToList());
}

我的编辑视图:

@model IList<Item> 
@{ 
    ViewBag.Title = "Edit sheet";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm("EditItems", "Controller", FormMethod.Post))
{
    <table class="table table-sm">
            <tr>
                <th>
                    floatValue1
                </th>
                <th>
                    stringValue1
                </th>
                <th>
                    floatValue2
                </th>
            </tr>

            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)

            @for(int i= 0; i < Model.Count(); i++)
            {
                <tr>
                    <td>
                        @Html.EditorFor(x => x[i].floatValue1)
                    </td>
                    <td>
                        @Html.EditorFor(x => x[i].stringValue1)
                    </td>
                    <td>
                        @Html.EditorFor(x => x[i].floatValue2)
                    </td>
                    <td>
                        @Html.EditorFor(x => x[i].doubleValue1, new { @readonly = "readonly" })
                    </td>
                </tr>
            }
    </table>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-secondary btn-lg mt-1" />
        </div>
    </div>
}

我的HTTP POST控制器操作:

        public ActionResult EditItems(IList<Item> table)
        {

            return View(new List<Item>());
        }

我在操作中得到一个List<Item>的值,但是列表中的每个项目的字段都为0或为空。

1 个答案:

答案 0 :(得分:1)

您的模型应该具有getter和setter,以便模型绑定器可以设置值。当您的模型符合以下条件时,它应该可以工作:

public float floatValue1 { get; set; }
public string stringValue1 { get; set; }
public float floatValue2 { get; set; }
public double doubleValue1 { get; set; }

在C#中,通常以大写字母开头这样的属性,因此我建议您进行更改。