邮政JSON阵列控制器的MVC [英] Post JSON array to mvc controller

查看:103
本文介绍了邮政JSON阵列控制器的MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想张贴JSON数组到MVC控制器。但无论我怎么努力,一切都是0或空的。

I'm trying to post a JSON array to a 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.

这是我的Java code:

This is my java code:

$(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;
    });
});

这是我的看法code:

This is my view code:

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

我究竟做错了什么?

What am i doing wrong?

推荐答案

有很多的问题与你的code。让我们先从标记。你有一个表,这个表的每一行里面要包括隐藏字段。除非你已经很难codeD上的 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 事件$ C>的提交按​​钮的事件。这样做的原因是,因为一个形式例如可以提交如果用户presses回车键而焦点是里面的一些输入字段。在这种情况下,点击事件不会被触发。

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)
{
    ...
}

和这里的最后一个客户端code:

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

显然,如果您的视图模型是不同的(你有没有在你的问题显示了它),你可能需要,使之与结构相匹配,以适应code,否则默认模式粘结剂将无法反序列化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天全站免登陆