Accessing Server Tags inside Javascript in MVC project
I'd like to use some server tags inside a Ja开发者_开发百科vascript function:
<%=Model.HtmlProperty%>
In the past I have stored this value in a hidden input field, but when a property contains HTML you get problems with special characters such as quotes. I would like to avoid having to encode and decode in the controller to avoid problems with special characters.
Rick Strahl has a couple posts on this problem in a web forms project, but I'm looking for an elegant solution for an MVC project.
UPDATE: Robert Harvey's answer below suggests to encode the html. Again, that isn't what I want to do. Ultimately, I'm trying to inject html script into an fckeditor instance. This must be done in javascript. I'm trying to figure out how to access the value of <%=Model.HtmlProperty%>
inside javascript without storing encoded text in a hidden input element.
Borrowing from Rick Strahl's post, and changing the calling signature a bit, the function for encoding a javascript string (after changing it into an extension method for the Html class) looks like this:
public static string EncodeJsString(this HtmlHelper h, string s)
{
StringBuilder sb = new StringBuilder();
sb.Append("\"");
foreach (char c in s)
{
switch (c)
{
case '\"':
sb.Append("\\\"");
break;
case '\\':
sb.Append("\\\\");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
default:
int i = (int)c;
if (i < 32 || i > 127)
{
sb.AppendFormat("\\u{0:X04}", i);
}
else
{
sb.Append(c);
}
break;
}
}
sb.Append("\"");
return sb.ToString();
}
Which should allow you to call it like this:
<%= Html.EncodeJsString(Model.HtmlProperty) %>
It seems that what I was hoping to do - using server tags inside javascript - is not possible. I had been storing the string inside a hidden input element, and as per queen3's comment, it seems that I will have to keep on doing what I have been doing all along. Thanks everyone for your input.
Use HTMLHelper to write your script on the fly..
public static string WriteLightboxScript(this HtmlHelper helper, string galleryName)
{
var builder = new TagBuilder("script");
builder.MergeAttribute("type", "text/javascript");
builder.SetInnerText("$(function() {$('a[rel=" + galleryName + "]').lightBox();});");
return builder.ToString(TagRenderMode.Normal);
}
精彩评论