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

1
  • can you show me please all your javascript code?? please! Commented Jan 19, 2011 at 12:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.