Skip to content Skip to sidebar Skip to footer

Add Html.partial To Javascript

I want to set a string in Javascript with an ASP.NET Html.Partial View. The problem is that Html.Partial gives an HtmlString and not a Javascript string which i can handle for exam

Solution 1:

Couldn't you just use something like:

var badge='@Html.Partial("_UserBadge",User.Identity.Name).Replace( "\n", "\\n" ).Replace( "'", "\\'" )';

You suggest in your question that you want the result to be:

'<div style="..">   '+
'...some more lines html...   '+
'</div>  ';

but note that this is equivalent to:

'<divstyle="..">   ...some more lines html...   </div>  ';

which might not be what you actually want (since this is different from the _UserBadge page).

What you probably actually want is something more like this:

'<divstyle="..">\n...some more lines html...\n</div>';

The example replaces newline characters with "\n" which will be interpreted by javascript as a newline character. Finally, you'll need to replace single quotes with "\'" to ensure that you don't accidentally terminate the string before you meant to.

Solution 2:

I think you could use Json.NET for serializing objects to json (it will escape all the string characters).

Something like:

@using Newtonsoft.Json

myfunction= function () {
   ...
   var badge=@(Html.Raw(JsonConvert.SerializeObject(Html.Partial("_UserBadge",User.Identity.Name))));
   ....
   $("#myNode").append(badge);
};

Post a Comment for "Add Html.partial To Javascript"