我想限制DropDownList
中显示的字符数:
@Html.DropDownList("domaines", Model.Domaines, new { @class = "form-control", @id = "domaines", autocomplet = "autocomplet",maxlength = 21 })
这是情景:
我该怎么做?
答案 0 :(得分:2)
在将模型发送到视图之前,您需要准备模型。你need to pass an IEnumerable<SelectListItem>
to DropDownList()
, not your own type。您可以使用SelectList(IEnumerable, string, string)
constructor。
如何使用省略号截断字符串已在How do I truncate a .NET string?和Ellipsis with C# (ending on a full word)中得到解答。
在您的控制器中:
// ... initialize model.
foreach (var domainModel in model.Domaines)
{
// Assuming the display member you want to truncate is called `DisplayString`.
// See linked questions for Truncate() implementation.
domainModel.DisplayString = domainModel.DisplayString.Truncate(18);
}
// Assuming the `Domaines` type has a `Value` member that indicates its value.
var selectList = new SelectList(model.Domaines, "Value", "DisplayString");
// Add a `public SelectList DomainSelectList { get; set; }` to your model.
model.DomainSelectList = selectList;
return View(model);
在您看来:
@Html.DropDownList("domaines", Model.DomainSelectList, new { ... })