Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Html.Raw in MVC Razor DropDownList?

I'm using DropDownList in MVC Razor, and am having problems with the automatic HTML encoding. My code looks like:

@Html.DropDownList("MyList", Model.DropdownNamesAndValues)

Which works fine, except that a SelectListItem.Text property in the DropdownNamesAndValues list may have HTML bold or italic tags in it. These are currently appearing literally in the dropdown (e.g. <i>hello</i> world ) . What I'd like to know how to do is:

  • How to apply @Html.Raw to each of the SelectListItem.Text properties ?
  • Failing that, is there an easy way to just remove the HTML tags instead ? Basically anything instead of showing them literally as at present.
like image 931
Michael Low Avatar asked Nov 23 '11 08:11

Michael Low


4 Answers

may be you need to remove those html elements from you model itself, then bring cleaned data to append in view dropdownlist

like image 98
manny Avatar answered Oct 12 '22 20:10

manny


Write in the controller a method that looks for <*> and </*> subsets in your strings, and removes them.

I don't think you can add html tags to drop down list.

like image 31
gdoron is supporting Monica Avatar answered Oct 12 '22 20:10

gdoron is supporting Monica


You should strip the html tags out before the view. In either the controller or preferably in the model where you are hopefully getting the values.

like image 1
James Hull Avatar answered Oct 12 '22 20:10

James Hull


If you want to allow the HTML to be emitted without encoding, you could extend the DropDownList helper so you can exclude the call to HttpUtility.HtmlEncode() in the ListItemToOption method. It does seem like a lot of code you'll have to use, but extending it (for a different purpose) is described in this article.

like image 1
JustinStolle Avatar answered Oct 12 '22 18:10

JustinStolle