【问题标题】:How to create a edit view for multiple model objects with no primary key?如何为没有主键的多个模型对象创建编辑视图?
【发布时间】:2025-12-31 20:55:01
【问题描述】:

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

如何将模型绑定到视图,以便在视图中进行编辑后,我可以在 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&lt;Item&gt; 的值,但列表中的每个项目的字段都有 0 或 null 值。

【问题讨论】:

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


    【解决方案1】:

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

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

    在 C# 中,此类属性通常以大写字母开头,因此我建议您更改它。

    【讨论】:

    • 不,我不介意是否将整个列表发回。我的问题是我在编辑控制器操作中返回的列表没有字段值。
    • 对我的误解表示歉意。你是对的,你的代码几乎可以工作了。我已经更新了我的答案。