2

I need to populate an attribute of a form tag generated with Html.BeginForm with a JSON object. I can't find a way to get it to print the attribute value without encoding it. I have tried with and without Html.Raw and in both cases the quotes inside the JSON still get escaped. This occurs with both single and double quotes. The problem in the following example is with the "data-feedback" attribute.

Code:

@using (Html.BeginForm("SendMessage", "ContactForm", FormMethod.Post, new { enctype = "multipart/form-data", id = "ContactForm", role = "form", @class = "form-element", data_toggle = "validator", data_feedback = Html.Raw("{'success': '', 'error': 'glyphicon-exclamation-sign'}") })) 

Result:

<form action="/contactform/sendmessage" class="form-element" data-feedback="{&#39;success&#39;: &#39;&#39;, &#39;error&#39;: &#39;glyphicon-exclamation-sign&#39;}" data-toggle="validator" enctype="multipart/form-data" id="ContactForm" method="post" role="form"> 
5
  • Have you tried @Html.Raw(Json.Encode("{...}")))?CommentedFeb 1, 2019 at 23:27
  • No repro in a fiddle. Probably you should try custom HTML helper inherited from BeginForm helper to prevent double-encoded string in Razor view.CommentedFeb 4, 2019 at 1:55
  • @chakeda I just tried your suggestion but unfortunately it still encodes the JSON encoded version. Thanks though!
    – Spew Pipe
    CommentedFeb 4, 2019 at 15:46
  • Hmm have you tried a NewtonSoft parse? stackoverflow.com/a/18831645/4378740CommentedFeb 4, 2019 at 15:57
  • 1
    @chakeda The limitation I am hitting is not with encoding the JSON, it's that I need whatever is passed in for the value to not get HTML encoded. Html.BeginForm doesn't seem to care what the value of the attribute is or how it is formatted, it HTML encodes the value regardless. For now I have worked around the issue by using JavaScript to add the attribute after the closing form tag. Thank you though!
    – Spew Pipe
    CommentedFeb 5, 2019 at 17:43

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.