How to use Html.Raw in MVC Razor DropDownList?

2019-06-18 23:43发布

问题:

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.

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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.