locked
Custom TagHelper Attribute with Single Quotes RRS feed

  • Question

  • User1706137234 posted

    Is there a way to set the output quotes for output.Attributes.Add("foo", "bar") for an attribute tag helper? My primary use case is to serialize json data to an html data- attribute.

    I start with...
    <div my-foo-bar />

    I can get...
    <div foo="bar" /> (double quotes)

    I would like...
    <div foo='bar' /> (single quotes)

    Friday, October 4, 2019 5:12 AM

Answers

  • User1706137234 posted

    Thanks to everyone for the response. I guess I didn't really want/need single quotes for the attributes. I just wanted the json to encode properly to the attribute and be available as an object in script on the client. I was already using HttpUtility.HtmlEncode() for the json data. However, it wasn't until I also included IHtmlHelper.Raw(), that everything worked out.

    To output the json to an attribute from a tag helper (same as I have done in the past directly in the view), I just needed to do the following; 

    var attributeValue = _htmlHelper.Raw(HttpUtility.HtmlEncode(json)); 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 15, 2019 3:43 AM

All replies

  • User753101303 posted

    Hi,

    Never tried yet. You really found a problem? I would expect the value to be properly encoded/decoded so that it doesn't cause any issue...

    Friday, October 4, 2019 9:36 AM
  • User-474980206 posted

    if you put json in a html attribute, you should use HttpUtility.HtmlEncode() of the json data. even when using single quotes, you should html encode quotes.

    Friday, October 4, 2019 4:55 PM
  • User711641945 posted

    Hi Simplifying,

    You mean that you want to use <div my-foo-bar /> in .cshtml file and it would render to <div foo='bar' /> in browser? Could you share why do you want to set output single quote?

    By default,if you use <div foo='bar' /> in .cshtml file,the browser would render to double quotes.

    output.Attributes.Add("foo", "bar") is used to add a new attribute.It is not related to set output quotes.

    Best Regards,

    Rena

    Tuesday, October 8, 2019 9:44 AM
  • User1706137234 posted

    Thanks to everyone for the response. I guess I didn't really want/need single quotes for the attributes. I just wanted the json to encode properly to the attribute and be available as an object in script on the client. I was already using HttpUtility.HtmlEncode() for the json data. However, it wasn't until I also included IHtmlHelper.Raw(), that everything worked out.

    To output the json to an attribute from a tag helper (same as I have done in the past directly in the view), I just needed to do the following; 

    var attributeValue = _htmlHelper.Raw(HttpUtility.HtmlEncode(json)); 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 15, 2019 3:43 AM