Render apostrophe through MvcHtmlString.Create()

2019-08-09 23:33发布

问题:

I have a string which looks like: Foo's Bazz

I am using a custom HtmlHelper to render this text inside of a div element:

public static MvcHtmlString DisplayWithReadonlyIdFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
    string readonlyId = "Readonly" + helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));

    TagBuilder tag = new TagBuilder("div");
    tag.MergeAttributes(new RouteValueDictionary(htmlAttributes));

    tag.SetInnerText(helper.DisplayFor(expression).ToString());

    return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}

Using this code, I still see the HTML representation of apostrophe, not the apostrophe itself.

I tried following the advice found in Escaping single quote from an MVC 3 Razor View variable by calling JavaScriptStringEncode. I've also trying HtmlDecode. Neither have any effect.

I was wondering what I need to do to achieve rendering the actual apostrophe instead of just the HTML mark-up inside of my div element.

回答1:

Did you try below ?

HttpUtility.HtmlDecode("Some value");
HttpUtility.HtmlEncode("Some value");

Example

string value1 = "&lt;html&gt;";                 //&lt;html&gt;
string value2 = HttpUtility.HtmlDecode(value1); //<html>
string value3 = HttpUtility.HtmlEncode(value2); //&lt;html&gt;

MvcHtmlString.Create(HttpUtility.HtmlDecode("Some value"))