Reputation: 11
I use System.Web.Script.Serialization library to encode elements from C#. How can I decode it from JS function.
for example I have :
JavaScriptSerializer js = new JavaScriptSerializer();
string ModelString= js.Serialize(Model);
and want in JS to do:
var element=decode('@ModelString');
Upvotes: 0
Views: 1186
Reputation: 14967
You can create a method for return serialize Model:
using System.Web.Script.Serialization;
namespace SO11444045.Models
{
public class HomeIndex
{
public HomeIndex()
{
this.Name = "Alfred";
this.Age = 33;
}
public string Name { get; set; }
public int Age { get; set; }
public string Me()
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize((object)this);
}
}
}
and get Modelo instance in View:
@model SO11444045.Models.HomeIndex
@{
ViewBag.Title = "Index";
}
<script type="text/javascript">
var json = @Html.Raw(Model.Me());
alert(json.Name);
</script>
Upvotes: 0
Reputation: 2541
You need to use jQuery.
var _Model=$parseJSON(ModelString);
then you can use:
_Model.Name;
_Model.Address; //etc...
I hope this is what u want...
Upvotes: 2
Reputation: 720
You can do something like this in your view:
var element = @Html.Raw(Json.Encode(Model))
Where "Model" is an Object. It does not have to be serialized in this case, Json.Encode() takes care of that.
Alternatively if you want to serialize your object in the controller you can do something like this in the view:
var element = @Html.Raw(ModelString)
Upvotes: 0