It’s easy to return a complex C# object from an MVC controller as JSON for your client-side JavaScript to consume. Just use the Json() method of the Controller class to serialize your C# object to JSON and return it as an ActionResult. You can use jQuery to wire up the AJAX and call the controller method via HTTP GET or POST using $.get() and $.post() respectively. The trick is to set the type parameter of the jQuery AJAX method that you’re using to ‘json’. This will tell jQuery to expect JSON as the response data and deserialize/evaluate it as JavaScript. Check it:
jQuery Javascript:
$.get('/MyController/GetSomething, { name: 'value' }, function(data) { alert(data.Name); }, 'json'); // Set the type to 'json'!
MVC Controller C#:
public ActionResult GetSomething(string name) { return Json(new { Name = name, Description = "hey!" }); }
'''''''''''''''''''''''''''';;;;;;;;;;;;;;;;;""""""""""""""""""""""""""""""""
ReplyDeleteJavascript code has at least two errors:
ReplyDelete1) closing appostroph in url is absent
2) if controller named as HomeController then url should be: '/Home/GetSomething'
I have tried this with the corrections mentioned above, but with no luck!
ReplyDeleteIf you're using MVC2 and you're calling the action with a GET, you'll need to explicitly allow GET requests otherwise you'll get an exception:
ReplyDeletereturn Json(new { ... }, JsonRequestBehavior.AllowGet);
Thanks alot, but Still it dont work. I am using MVC2 and jQuery 1.4.1.
ReplyDeleteAnyone have a tip for me?
Se my code below:
Here is my action method in controller:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult ListSensorValues(int MeasurementID)
{
var SensorValues = Repository.ListSensorValues(MeasurementID);
var JsonSensorValues = from sv in SensorValues
select new JsonSensorValue
{
Latitude = (double) sv.Latitude,
Longetude = (double) sv.Longetude,
Friction = (double) sv.Value
};
return Json(JsonSensorValues.ToList(), JsonRequestBehavior.AllowGet);
}
And here is my javascript:
var id = "<%: Model.Measurement.MeasurementID %>";
$.get("/Measurements/ListSensorValues", { MeasurementID: 'id' },
function (SensorValues) {
alert("Hei");
}, "json");
Try using $.getJSON() instead. check jquery docs for details...
ReplyDeleteThanks for helping me out. I finally found the reason to my problem. The id parameter should not be passed as a string. This works fine:
ReplyDelete$.get("/Measurements/ListSensorValues", { MeasurementID: id },
function (SensorValues) {
alert("Hei");
}, "json");
Hi I want to bind this data to grid, How can do?
ReplyDelete