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 example with JQuery.
Javascript code:
myfunction= function () {
...
var badge=@Html.Partial("_UserBadge",User.Identity.Name).ToString();
....
$("#myNode").append(badge);
};
Html-Partial "_UserBadge.cshtml":
@model WT.Models.ttUser
<div style="..">
...some more lines html...
</div>
My problem is that ' at beginning and '+ at the end of each line isn't added. How can i resolve the problem?
The code results to:
var badge=
<div style="..">
...some more lines html...
</div>;
instead of a javascript string:
var badge=
'<div style=".."> '+
'...some more lines html... '+
'</div> ';
Couldn't you just use something like:
You suggest in your question that you want the result to be:
but note that this is equivalent to:
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:
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.I think you could use Json.NET for serializing objects to json (it will escape all the string characters).
Something like: