将 JSON 数组发布到 mvc 控制器 [英] Post JSON array to mvc controller

查看:27
本文介绍了将 JSON 数组发布到 mvc 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 JSON 数组发布到 MVC 控制器.但无论我尝试什么,一切都是 0 或 null.

I'm trying to post a JSON array to an MVC controller. But no matter what I try, everything is 0 or null.

我有一张包含文本框的表格.我需要所有这些文本框中的 ID 和值作为对象.

I have this table that contains textboxes. I need from all those textboxes it's ID and value as an object.

这是我的 Javascript:

This is my Javascript:

$(document).ready(function () {

    $('#submitTest').click(function (e) {

        var $form = $('form');
        var trans = new Array();

        var parameters = {
            TransIDs: $("#TransID").val(),
            ItemIDs: $("#ItemID").val(),
            TypeIDs: $("#TypeID").val(),
        };
        trans.push(parameters);


        if ($form.valid()) {
            $.ajax(
                {
                    url: $form.attr('action'),
                    type: $form.attr('method'),
                    data: JSON.stringify(parameters),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        $('#result').text(result.redirectTo)
                        if (result.Success == true) {
                            return fase;
                        }
                        else {
                            $('#Error').html(result.Html);
                        }
                    },
                    error: function (request) { alert(request.statusText) }
                });
        }
        e.preventDefault();
        return false;
    });
});

这是我的视图代码:

<table>
        <tr>
            <th>trans</th>
            <th>Item</th>
            <th>Type</th>
        </tr>

        @foreach (var t in Model.Types.ToList())
        {
            {
            <tr>
                <td>                  
                    <input type="hidden" value="@t.TransID" id="TransID" />
                    <input type="hidden" value="@t.ItemID" id="ItemID" />
                    <input type="hidden" value="@t.TypeID" id="TypeID" />
                </td>
            </tr>
           }
        }
</table>

这是我试图接收数据的控制器:

This is the controller im trying to receive the data to:

[HttpPost]
public ActionResult Update(CustomTypeModel ctm)
{


   return RedirectToAction("Index");
}

我做错了什么?

推荐答案

您的代码存在很多问题.让我们从标记开始.您有一个表格,并且在该表格的每一行中都包含隐藏字段.除非您对那些隐藏元素的 id 属性进行了硬编码,这意味着您可能会在标记中得到多个具有相同 id 的元素,从而导致标记无效.

There are lots of issues with your code. Let's start with the markup. You have a table and inside each row of this table you are including hidden fields. Except that you have hardcoded the id attribute of those hidden elements meaning that you could potentially end up with multiple elements with the same id in your markup which results in invalid markup.

那么让我们首先修复您的标记:

So let's start by fixing your markup first:

@foreach (var t in Model.Types.ToList())
{
    <tr>
        <td>                  
            <input type="hidden" value="@t.TransID" name="TransID" />
            <input type="hidden" value="@t.ItemID" name="ItemID" />
            <input type="hidden" value="@t.TypeID" name="TypeID" />
        </td>
    </tr>
}

好的,现在您有了有效的标记.现在让我们继续讨论当点击某个 submitTest 按钮时将触发的 javascript 事件.如果这是表单的提交按钮,我建议您订阅表单的 .submit 事件而不是其提交按钮的 .click 事件.这样做的原因是因为例如如果用户在焦点位于某个输入字段内时按下 Enter 键,则可以提交表单.在这种情况下,您的点击事件不会被触发.

Alright, now you have valid markup. Now let's move on to the javascript event which will be triggered when some submitTest button is clicked. If this is the submit button of the form I would recommend you subscribing to the .submit event of the form instead of the .click event of its submit button. The reason for this is because a form could be submitted for example if the user presses the Enter key while the focus is inside some input field. In this case your click event won't be triggered.

所以:

$(document).ready(function () {
    $('form').submit(function () {
        // code to follow

        return false;
    });
});

好的,接下来是您需要收集表内隐藏元素的值并将它们放入一个 javascript 对象的部分,我们随后将 JSON 序列化并作为 AJAX 请求的一部分发送到服务器.

Alright, next comes the part where you need to harvest the values of the hidden elements which are inside the table and put them into a javascript object that we will subsequently JSON serialize and send as part of the AJAX request to the server.

让我们继续:

var parameters = [];
// TODO: maybe you want to assign an unique id to your table element
$('table tr').each(function() {
    var td = $('td', this);
    parameters.push({
        transId: $('input[name="TransID"]', td).val(),
        itemId: $('input[name="ItemID"]', td).val(),
        typeId: $('input[name="TypeID"]', td).val()
    });
});

到目前为止我们已经填写了我们的参数,现在让我们将它们发送到服务器:

So far we've filled our parameters, let's send them to the server now:

$.ajax({
    url: this.action,
    type: this.method,
    data: JSON.stringify(parameters),
    contentType: 'application/json; charset=utf-8',
    success: function (result) {
        // ...
    },
    error: function (request) { 
        // ...
    }
});

现在让我们转到服务器端.和往常一样,我们首先定义一个视图模型:

Now let's move on to the server side. As always we start by defining a view model:

public class MyViewModel
{
    public string TransID { get; set; }
    public string ItemID { get; set; }
    public string TypeID { get; set; }
}

和一个控制器动作,它将收集这个模型:

and a controller action that will take a collection of this model:

[HttpPost]
public ActionResult Update(IList<MyViewModel> model)
{
    ...
}

这是最终的客户端代码:

And here's the final client side code:

$(function() {
    $('form').submit(function () {
        if ($(this).valid()) {
            var parameters = [];
            // TODO: maybe you want to assign an unique id to your table element
            $('table tr').each(function() {
                var td = $('td', this);
                parameters.push({
                    transId: $('input[name="TransID"]', td).val(),
                    itemId: $('input[name="ItemID"]', td).val(),
                    typeId: $('input[name="TypeID"]', td).val()
                });
            });

            $.ajax({
                url: this.action,
                type: this.method,
                data: JSON.stringify(parameters),
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                    // ...
                },
                error: function (request) { 
                    // ...
                }
            });
        }
        return false;
    });
});

显然,如果您的视图模型不同(您没有在问题中显示它),您可能需要调整代码以使其与您的结构相匹配,否则默认模型绑定器将无法反序列化 JSON.

Obviously if your view model is different (you haven't shown it in your question) you might need to adapt the code so that it matches your structure, otherwise the default model binder won't be able to deserialize the JSON back.

这篇关于将 JSON 数组发布到 mvc 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆