ISSUE :
 
Profile photo
Submitted by Bikram Shrestha
on October 5th, 2012 at 16:38:39 EST

Avoid HTML encoding with custom MVC HtmlHelper extension

I am trying to create custom HtmlHelper extension for MVC application. But my output is always HTML encoded and my html tag for example <br/> becomes &lt;br/&gt;
How do I avoid HTML encoding with output of my HtmlHelper extension? I am using ASP.NET 4.0 with MVC 3.0.

code sample:

public static class MyExtensions
{
public static string DisplayStudentList(this HtmlHelper html, StudentInfo[] studentList)
{
if (studentList != null && studentList.Length > 0)
{
StringBuilder sb = new StringBuilder();
foreach (StudentInfo studentInfo in studentList)
{
sb.Append(studentInfo.FirstName);
sb.Append(" - ");
sb.Append(studentInfo.LastName);
sb.Append("<br/>");
}
return sb.ToString();
}
return String.Empty;
}
}


Profile photo
Replied by SBajra
on October 8th, 2012 at 09:38:37 EST
Return your String as MvcHtmlString. MvcHtmlString is HTML-encoded string that can not be encoded again.
For example:

return MvcHtmlString.Create(sb.ToString());
Accepted Answer
Accepted
 Answer

Profile photo
Replied by Bikram Shrestha
on October 8th, 2012 at 15:41:33 EST
Thanks. MvcHtmlString is what I needed.