views:

75

answers:

1

Here is the scenario

In MVC, it is easy to return a Javascript to be executed on the client

public ActionResult DoSomething()
{       
    return JavaScript("alert('Hello world!');");            
}

On the client, I have a Javascript that takes a JSon object as parameter

Something similar to this :

function open(options) {...}

I wanted to call this function from my action passing it a json object generated on the server so I wrote this

public ActionResult DoSomething()
{
      var viewData = new {...};
      return JavaScript( "open('" + Json(viewData) + "')" );          
}

However, when my Javascript function get called, I don't get any data but this: open('System.Web.Mvc.JsonResult')

I will appreciate any help on this matter

Thanks

A: 

The Json method returns a JsonResult. Not a JSON string. You could use the JavaScriptSerializer

public ActionResult DoSomething()
{
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      var viewData = new {...};
      return JavaScript( "open('" + serializer.Serialize(viewData) + "')" );          
}

Depending on how your client side open method works you may need to send the json data as a json object instead of a string by simply removing the ' around the method argument.

Jesper Palm
I removed the ' around the method argument and this effectively worked.Thank you so much for your help