简体   繁体   中英

pass json object to controller action with get request

I am working with asp.net mvc4. I have an action method which is a get method as it returns a an mvc view that is called from JavaScript/Jquery.

The javascript makes a get request to the controller action. I have a json object that I would like to pass to the mvc action. But as its a get request, as I need to return a view from it, it is posing difficult.

Is it possible to pass a json object that maps to an object on the signature of the controller action? I was looking libraries that may help such as http://benalman.com/projects/jquery-bbq-plugin/

Any tips or ideas?

you could use something like servicestack http://www.servicestack.net/ this takes care of everything, and does it very well, as an alternative there is the MVC API options, but servicestack is better at this.

I am sure if you look at this project, you will either get great ideas from it, or learn to decouple your data driven code, away from your UI project.

You dont need any external APIs to do that. All you need to do is make an c# object with the same property and name as the JSON Object. For Eg Create an Object as

public class MyObject{
    public string MyProperty1{get; set;}
    public string Property2{get; set;}
}

And creating object in the jquery is all correct i assume and use jquery syntax like
as below

$.get('@Url.Action("MyAction","MyController")',
    {myObject: jqueryObject},
    function(resp){$("#myDiv").innerHTML(resp);});

And in case of Action use function declaration like

public ActionResult MyAction(MyObject myObject)
{
    // your code here
    return PartialView("_MyPartialView", myModelForPartialView);
}

BTW this way works for both Get and Post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM