【发布时间】:2025-12-31 20:55:01
【问题描述】:
我正在服务器端进行一些计算并在视图中显示表格。我希望能够在单个视图中编辑表格的每一行。
如何将模型绑定到视图,以便在视图中进行编辑后,我可以在 POST 控制器操作中获得模型对象的列表?
我的模特:
public class Item
{
public float floatValue1;
public string stringValue1;
public float floatValue2;
public double doubleValue1;
}
从这个模型中,我创建了一个表格视图,其中列出了 HTML 表格中的值。
但是,在编辑视图中我不需要编辑每个字段。例如,只有floatValue1、stringValue1、floatValue2 需要可编辑。 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 或 null 值。
【问题讨论】:
标签: c# asp.net asp.net-mvc