1

I'd like to limit the number of displayed characters in DropDownList :

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

this is the scenario :

  1. if the number of characters <= 18 : the whole word is displayed
  2. Else if number of characters > 18 : the first 18 characters will be displayed concatenated to an ellipsis (...).

How can I do this?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191

1 Answers1

2

You need to prepare your model before you send it to the view. You need to pass an IEnumerable<SelectListItem> to DropDownList(), not your own type. You can use the SelectList(IEnumerable, string, string) constructor for that.

How to truncate strings with ellipsis has been answered in How do I truncate a .NET string? and Ellipsis with C# (ending on a full word).

In your controller:

// ... 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);

In your view:

@Html.DropDownList("domaines", Model.DomainSelectList, new { ... }) 
Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272