Using C# object in Javascript in ASP.NET MVC

  1. Using @Html.Raw():
    dosomething(‘@Html.Raw(Model.UrProperty)’);
  2. Using JavaScriptSerializer() in the model:

Model:

public class MyModel
{
public string JsonData{get;set;}
}

Controller:

public class mycontroller : controller
{
public ActionResult WhatToDo()
{
var myModel= new MyModel;
var serializer = new JavaScriptSerializer();
myModel.JsonData = serializer.Serialize(data);
return PartialView(myModel);
}
}

VIEW:

dosomething(‘@Model.JsonData’)

Using this method, then your function will work as expected:

function dosomething(obj)
{
var myJsonResult = obj.JsonData;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s