问题
I use Html.Raw(Json.Encode
in my Javascript to grab the contents of the ViewModel property passed to the View in my MVC 3 asp.net (razor) application as follows:
var state = @(Html.Raw(Json.Encode(Model.State)));
State is defined in my Model as such
public class IndexViewModel
{
//..other props
public string State { get; set; }
}
It works like a charm in FF, IE8 but chokes on IE 9.
Is there anything I should know about the above code that was changed in IE 9 so this no longer works? If so, what would be the alternative to grab ViewModel data in your JS?
回答1:
Here is an alternative
view model
public class StuffVM : AsSerializable
{
public List<Stuff> StuffList { get; set; }
}
base class
public abstract class AsSerializable
{
public string AsJson()
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(this);
}
}
view
<script>
var ViewModelData = @( Html.Raw(Model.StuffVM.AsJson()) );
</script>
回答2:
I really like Travis's solution. An alternative (if you're using C# 3.0 or newer) is to use an extension method.
public static class ObjectExtensions
{
static public string ToJson(this object model)
{
return new JavaScriptSerializer().Serialize(model);
}
}
This is a completely philosophical choice however... whether to use inheritance or an extension method. My personal choice is the extension method because it feels slightly cleaner and less coupled. By that is just my opinion.
However, using Travis's method, you could decide to just create one instance of the serializer and reuse that instance if you need to do more than one serialization which would be more efficient memory-wise. If you did that with an extension method, it would not be thread-safe.
来源:https://stackoverflow.com/questions/11749103/html-rawjson-encode-and-internet-explorer-9