我有一个 ASP.NET MVC3 Razor View ,它在 jQuery UI Accordion 中为客户列表呈现编辑器。目前,类似客户属性的所有客户端 ID 在呈现的 html 中都是相同的。出于明显的原因,我想改变这一点。
我的主要观点如下:
<div id="accordionKlanten">
@foreach (var customer in Model.Customers)
{
<h3><a href="#">@customer.Name</a></h3>
<div>@{ Html.RenderPartial("CustomerData", customer); }</div>
}
</div>
在我的 CustomerData
View (大大简化):
@using (Ajax.BeginForm("UpdateCustomer", ajaxOptions))
{
@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name)
<input type="submit" value="Opslaan" />
}
这一切都很完美:我可以发布到我的 UpdateCustomer
action 方法,绑定(bind)模型对象并返回呈现给客户端的局部 View 。
但是当我有三个客户时,这会在我的 html 中使用 id="Name"
呈现三个输入字段.出错的地方之一是 <label for="Name">...</label>
自 Name
起无效不是唯一的 ID。
有什么方法可以告诉 ASP.NET MVC3 呈现不同的 id
的(同时完整保留 name
属性,因为这些属性用于绑定(bind)到模型)?
为了完整起见,这里列出涉及的两个action方法:
// Returns view that renders editor for each customer.
public ActionResult Index()
{
var customers = _customerService.GetCustomers();
return View(new CustomersViewModel { Customers = customers });
}
// Updates a customer and returns a partial view.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateCustomer(CustomerDto customer)
{
// Update customer in database.
return PartialView("CustomerData", customer);
}
最佳答案
而不是在 View 中编写丑陋的循环:
<div id="accordionKlanten">
@foreach (var customer in Model.Customers)
{
<h3><a href="#">@customer.Name</a></h3>
<div>@{ Html.RenderPartial("CustomerData", customer); }</div>
}
</div>
使用编辑器模板:
<div id="accordionKlanten">
@Html.EditorFor(x => x.Customers)
</div>
并在相应的编辑器模板 ( ~/Views/Shared/EditorTemplates/Customer.cshtml
) 中:
@model Customer
<h3>
<a href="#">@customer.Name</a>
</h3>
<div>
@Html.EditorFor(x => x.FirstName)
</div>
<div>
@Html.EditorFor(x => x.LastName)
</div>
...
现在 Customer
编辑器模板将为 Customers
的每个元素自动执行模型上的集合属性。唯一的要求是遵守命名约定:它应该位于 ~/Views/Shared/EditorTemplates
中。文件夹,它应该被命名为收集项的类型。例如,如果属性是 IEnumerable<CustomerViewModel>
,编辑器模板应命名为 CustomerViewModel.cshtml
并且显然被强类型化为 CustomerViewModel
.
就是这样。现在不仅您已经清理了 View ,而且还将使用专有名称。
关于asp.net-mvc - 重复项目列表时在 ASP.NET MVC3 中生成不同的客户端 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5663674/