使用jquery和ajax将json对象发布到mvc控制器

时间:2022-12-01 15:49:23

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

我试图将表单中的一些值提交给我的mvc控制器。

Here is my controller:

这是我的控制器:

 //Post/ Roles/AddUser
    [HttpPost]       
    public ActionResult AddUser(String json)
    {
        Log.submit(json);            
        return View();
    }

here is the js:

这是js:

<script>
function submitForm() {

    var usersRoles = new Array;
    $("#dualSelectRoles2 option").each(function () {
        usersRoles.push($(this).val());
    });
    console.log(usersRoles);

    jQuery.ajax({
        type: 'POST',
        url: "@Url.Action("AddUser")",
        contentType: "application/json; charset=utf-8",
        datatype: 'json',
        data: JSON.stringify(usersRoles),
        success: function (data) { alert(data); },
        failure: function (errMsg) {
            alert(errMsg);
        }
    });
}

When I debug on the controller I get my parameter to be null? The console.log(usersRoles) gives me data.

当我在控制器上调试时,我的参数为null?日志(usersRoles)为我提供数据。

What am I doing incorrectly?

我做错了什么?

How can I receive a json object in the controller?

如何在控制器中接收json对象?

3 个解决方案

#1


25  

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

我在您的代码中看到,您试图传递一个数组来POST操作。在这种情况下,遵循下面的工作代码-

<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 -

然后当你点击按钮-

使用jquery和ajax将json对象发布到mvc控制器

#2


9  

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

与接收json字符串相比,模型绑定更好。例如:

[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>

#3


3  

What am I doing incorrectly?

我做错了什么?

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

您必须将html转换为javascript对象,然后再将其转换为json格式的JSON.Stringify。

How can I receive a json object in the controller?

如何在控制器中接收json对象?

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;
}

#1


25  

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

我在您的代码中看到,您试图传递一个数组来POST操作。在这种情况下,遵循下面的工作代码-

<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 -

然后当你点击按钮-

使用jquery和ajax将json对象发布到mvc控制器

#2


9  

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

与接收json字符串相比,模型绑定更好。例如:

[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>

#3


3  

What am I doing incorrectly?

我做错了什么?

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

您必须将html转换为javascript对象,然后再将其转换为json格式的JSON.Stringify。

How can I receive a json object in the controller?

如何在控制器中接收json对象?

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;
}