这就是AttributeEncode
助手所做的:
<option value="@Html.AttributeEncode(custString)">@cust.DisplayName</option>
但是,嘿,你在做什么?foreach 循环生成下拉列表???
尝试使用Html.DropDownListFor
助手并在为时已晚之前止血。这个助手做它的名字所暗示的。并负责编码和转义等。
所以简单地定义一个视图模型:
public class MyViewModel
{
public string CustomerId { get; set; }
public IEnumerable<SelectListItem> Customers { get; set; }
}
然后继续并让您的控制器操作填充并将此视图模型传递给视图:
public ActionResult Index()
{
IEnumerable<Customer> customers = ... fetch the domain model from your DAL or something
// map to a view model:
var viewModel = new MyViewModel
{
Customers = customers.Select(x => new SelectListItem
{
Value = x.CustID,
Text = string.Format("{0}%#%{1}%#%{2}", x.CustID, x.LName, x.FName)
})
};
// pass the view model to the view:
return View(viewModel);
}
在视图内部,当您需要生成下拉列表时,使用 DropDownListFor 助手:
@Html.DropDownListFor(x => x.CustomerId, Model.Customers)