Post a json object to mvc controller with jquery and ajax

后端 未结 3 1216
傲寒
傲寒 2020-12-18 17:57

I am trying to submit some values from a form to my mvc controller.

Here is my controller:

 //Post/ Roles/AddUser
    [HttpPost]       
    public Ac         


        
相关标签:
3条回答
  • 2020-12-18 18:47

    I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script>
        function submitForm() {
            var roles = ["role1", "role2", "role3"];
    
            jQuery.ajax({
                type: "POST",
                url: "@Url.Action("AddUser")",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(roles),
                success: function (data) { alert(data); },
                failure: function (errMsg) {
                    alert(errMsg);
                }
            });
        }
    </script>
    
    <input type="button" value="Click" onclick="submitForm()"/>
    

    And the controller action is going to be -

        public ActionResult AddUser(List<String> Roles)
        {
            return null;
        }
    

    Then when you click on the button -

    enter image description here

    0 讨论(0)
  • 2020-12-18 18:49

    What am I doing incorrectly?

    You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.

    How can I receive a json object in the controller?

    View:

    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>
    
    var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
    $.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });
    
    <form id="form1" method="post">
    <input name="OrderDate" type="text" /><br />
    <input name="Item[0][Id]" type="text" /><br />
    <input name="Item[1][Id]" type="text" /><br />
    <button id="btn" onclick="btnClick()">Button</button>
    </form>
    

    Controller:

    public void PostRawJson(string json)
    {
        var order = System.Web.Helpers.Json.Decode(json);
        var orderDate = order.OrderDate;
        var secondOrderId = order.Item[1].Id;
    }
    
    0 讨论(0)
  • 2020-12-18 18:52

    instead of receiving the json string a model binding is better. For example:

    [HttpPost]       
    public ActionResult AddUser(UserAddModel model)
    {
        if (ModelState.IsValid) {
            return Json(new { Response = "Success" });
        }
        return Json(new { Response = "Error" });
    }
    
    <script>
    function submitForm() {    
        $.ajax({
            type: 'POST',
            url: "@Url.Action("AddUser")",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: $("form[name=UserAddForm]").serialize(),
            success: function (data) {
                console.log(data);
            }
        });
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题