开发者

limit item length of a listbox in mvc 2

开发者 https://www.devze.com 2023-02-13 08:29 出处:网络
In my MVC 2 application i ahve a list box <%: Htm开发者_JS百科l.ListBoxFor(m => m.SelectedQuestionIds[cnt1], Model.QuestionList, new { @class = \"list_style\" })%>

In my MVC 2 application i ahve a list box

<%: Htm开发者_JS百科l.ListBoxFor(m => m.SelectedQuestionIds[cnt1], Model.QuestionList, new { @class = "list_style" })%>

i have limited my list box width with the style "list_style".

my problem is that some of the item in my listbox has length greater than my listbox width. i need to limit the length of the item shown with a '...' if the length is too long. so my text will be 'how are you ...' for 'How are you my dear friend are u okay!' thanks, regards


You should put this in an extension method, something like

public static class StringExtensions {

  public static string TrimLength(this String text, int length) {
    if (text != null && text.Length > length) {
      return text.Substring(0, length - 1);
    }
    return text;
  }

  public static string TrimLengthWithEllipsis(this String text, int length) {
    if (text != null) {
      return TrimLength(text, length) + "..."; 
    }
    return text;
  }

}

Then you can use

model.QuestionList = from question in model.Questions
                                     select new SelectListItem
                                     {
                                         Text=question.QuestionDescription.TrimLengthWithEllipses(48),
                                         Value=question.QuestionID.ToString()
                                     };

Much cleaner and more reusable.


idid this:

model.QuestionList = from question in model.Questions
                                         select new SelectListItem
                                         {
                                             Text=question.QuestionDescription.Length>48?question.QuestionDescription.Substring(0,47)+" ...":question.QuestionDescription,
                                             Value=question.QuestionID.ToString()
                                         };


http://blogs.msdn.com/b/sajoshi/archive/2010/06/15/asp-net-mvc-creating-a-single-select-list-box-and-showing-tooltip-for-lengthy-items.aspx

This might help!!!

0

精彩评论

暂无评论...
验证码 换一张
取 消