限制DropDownList中的字符数

时间:2015-04-23 15:56:02

标签: c# asp.net-mvc

我想限制DropDownList中显示的字符数:

@Html.DropDownList("domaines", Model.Domaines, new { @class = "form-control", @id = "domaines", autocomplet = "autocomplet",maxlength = 21 })

这是情景:

  1. 如果字符数<= 18 :显示整个字词
  2. 如果是字符数&gt; 18 :前18个字符将显示连接到省略号(...)。
  3. 我该怎么做?

1 个答案:

答案 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 { ... })