Deb
Deb

Reputation: 991

Razor Not Rendering HtmlHelper Extension Method Properly

I have a Extension method in my html helper class to render an Autocomplete. This works fine with aspx view engine in VS2008 & VS2010. The Autocomplete class has an overloaded ToString() method which outputs Raw Html.

However when i use Razor engine i don't get any visible output. Firebug shows the output of Extension method is Html Encoded as follow :(with all &lt, &gt..)

    <input class="AutoComplete" id="p_ename" name="p_ename" style="width: 190px" type="text" valuefield="p_empid"></input> <input id="p_empid" name="p_empid" type="hidden"></input> 
<script type='text/javascript'>$('#p_ename').autocomplete('/UserMst/GetEmployee', { dataType: 'json', scroll: true, parse: function(item, event) { $('#p_empid').val(''); var array = new Array(); if(item) for (var i = 0; item[i]; i++ ) { array[array.length] = { data: item[i], value: item[i], result: unescape(item[i].Text) }; } return array; }, formatItem: function(row) { return unescape(row.Text); } }).result(function(event, item, formatted) { $('#p_empid').val(item.Value); }).keyup(function() { if (window.event.keyCode != 13 && window.event.keyCode != 16 && window.event.keyCode != 20 && window.event.keyCode != 9 && window.event.keyCode != 27 && !(window.event.keyCode >= 112 && window.event.keyCode <= 123) && !(window.event.keyCode >= 37 && window.event.keyCode <= 40)) { $('#p_empid').val(''); } });
</script>

And this is how I call the method :

@Html.AutocompleteFor(m => m.p_empid, m => m.p_ename)
.setUrl(VirtualPathUtility.ToAbsolute("~/UserMst/GetEmployee"))
.setClass("AutoComplete").setStyle("width: 190px")

How do i fix this to work with Razor in MVC3 ?

Thanks

Upvotes: 1

Views: 1119

Answers (2)

Deb
Deb

Reputation: 991

Ok ! This is how i got it to work for now. Dont know whether it is a good solution or not. Posting the fix here for others who are facing the same problem.

i renamed the ToString() override method to MvcHtmlString ToHtml() and returned MvcHtmlString.Create(result.ToString()) instead of raw html as string.

Now i have to call it as

@Html.AutocompleteFor(m => m.p_empid, m => m.p_ename)
.setUrl(VirtualPathUtility.ToAbsolute("~/UserMst/GetEmployee"))
.setClass("AutoComplete").setStyle("width: 190px").ToHtml()

Razor renders it properly now.

Upvotes: 0

Pierluc SS
Pierluc SS

Reputation: 3176

Make sure you return an MvcHtmlString by using following:

public static MvcHtmlString HiText(this HtmlHelper obj) {
   string code = "<p>hi</p>";
   return MvcHtmlString.Create(code);
}

Upvotes: 2

Related Questions