I forked mvc4 MultiSelectList class in my project to implement ToMvcHtmlString method. How can I get pure html from inside of my MultiSelectList instance?
public MvcHtmlString ToMvcHtmlString()
{
return ???;
}
You could make use of the Extension method HtmlHelper.ListBox, to get an instance of the MvcHtmlString (generally used as @Html.ListBox() in the View today).
This extension method exists in the System.Web.Mvc.Html namespace on the HtmlHelper class. So, all you need to do is create the method as follows: - Passing in the HtmlHelper instance from your View generally used as @Html - Where name is an argument required by ListBox (either you could pass that in, or hardcode it in your class - preferably pass it into the method)
public MvcHtmlString ToMvcHtmlString(HtmlHelper helper, String name) {
return helper.ListBox(name, this);
}
However doing this defeats the purpose of returning a pure MvcHtmlString from within your own class. Because you still need to pass in the HtmlHelper which is available in the View, meaning you might as well use following code to achieve the same thing:
@Html.ListBox(...)
The HtmlHelper is necessary as it needs access to the View, as that could have additional information required in building/populating the List.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With