ASP.NET MVC and JQuery get info to controller

前端 未结 7 1395
轻奢々
轻奢々 2020-12-28 23:51

I am totally confused on how to do ajax stuffs with jQuery and it seems the more I try the more confused I get. At this point all I want to do is get data to my controller

7条回答
  •  一生所求
    2020-12-29 00:12

    So I was having a little bit of a time trying to figure out how to get data back from an AJAX call. I was passing an JSON object from the view to the controller, and then return the ID of the object when it's done.

    So, I finally got that working, and here's what I did on the view:

    var obj = {
       property1 : '',
       property2 : ''
    };
    
    $.ajax({
        // Returns the full url
        url: '@Url.Action("Method", "Controller")', 
        // Sends as a json object, I actually have an object that maps to my ViewModel, this is just for explaining
        data: obj, 
        // You are telling that you are receiving a json object
        dataType: 'json', 
        success: function (id) {
           // do code here with id
        }
    })
    

    For my controller, I returned a Json object and did an AllowGet as a JsonRequestBehavior

    public ActionResult Method (ViewModel vm)
    {
        int id = ... (do something with the vm)
        return Json(id, JsonRequestBehavior.AllowGet);
    }
    

    Edit: In addition, it appears you have POST as the type of request to the controller, and your controller method doesn't have the [HttpPost] annotation. That could also be the case.

    I hope this helps!
    Cheers!

提交回复
热议问题