Simply I want to have a property in my object serialized as a string instead of HtmlString(which it is).
The reasoning here is that the object is serialized in json, and the toString function is not returning the string contents of the object but rather '[object Object]'.
Alternatively, would it be possible to label the property as [Non-Serializable] and expose another property in its stead as the serializable version?
Thanks in advance
Edit: Example Code:
[Serializable]
public MyObject
{
public int id= 0;
public string name = "myName";
public HtmlString WishIWasAString = new HtmlString("notAString");
public string fakeHtmlString
{
get { return WishIWasAString.ToString(); }
}
}
Example Json:
{
id: 0,
name: 'myName'
wishIWasAString: {}
fakeHtmlString: 'n开发者_开发技巧otAString'
}
<script type="type/javascript">
var fooProperty = @Html.Raw(Json.Encode(Model.Foo));
</script>
or if you wanted to JSON serialize your entire model into a javascript variable:
<script type="type/javascript">
var model = @Html.Raw(Json.Encode(Model));
alert(model.Foo.Bar);
</script>
I found a solution to your question.
Use this class:
using System.Runtime.Serialization;
[DataContract]
public MyObject
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
public HtmlString MyHtmlContent { get; set; }
[DataMember(Name = "MyHtmlContent")]
private string serializedMyHtmlContent
{
get { return this.MyHtmlContent == null ? null : MyHtmlContent .ToString(); }
}
}
You will obtain this JSON:
{
Id: 1234,
Name: "Chris",
MyHtmlContent: "<p>Hello word</p>"
}
精彩评论