如何从jQuery传递结构化数据?

时间:2011-05-16 07:41:56

标签: jquery asp.net-mvc

这是我在jQuery中的代码

    function link() {


        var items = $.map($('.trSelected', grd), function (i) {
            return i.id.substr(3);
        });

        // alert(items.length);
        // alert(items.join(', '));


        $.ajax({ url: '/Pos/Link', type: 'POST', datatype: 'json',
            data: ( { PosId: '@Model.PosId', PosDetailIds: items } ),
            success: function (result) {
                grd.flexReload();                    
                alert('saved.');
            }
        });


    }

这是我在ASP.NET MVC控制器中的代码

    [HttpPost]
    public JsonResult Link(PosLink posLink) 
    {

        var svc = ServiceWirer.GetTxServiceInstance();
        svc.Pos_Link(posLink);

        return Json(new { HasError = false });
    }

由于我不熟悉的原因,只填充了PosId,未填充PosDetailIds

[UPDATE]

@Raynos:

我甚至试过这个,但也没有尝试过:

public JsonResult Link(Guid PosId, Guid[] PosDetailIds) 

仅填充PosId,PosDetailIds仍然为空

以下是PosLink结构:

public class PosLink
{
    public Guid PosId { get; set; }
    public Guid[] PosDetailIds { get; set; }
}

2 个答案:

答案 0 :(得分:4)

我现在解决了,我使用了jQuery的$ .param

  $.ajax({ url: '/Pos/Link', type: 'POST', datatype: 'json',
        data: $.param( { PosId: '@Model.PosId', PosDetailIds: items }, true ),
        success: function (result) {
            grd.flexReload();                    
            alert('saved.');
        }
    });

方式好多了:

  $.ajax({ url: '/Pos/Link', type: 'POST', datatype: 'json',
        traditional : true, // jQuery folks love PHP/Ruby very much :-)
        data:  { PosId: '@Model.PosId', PosDetailIds: items },
        success: function (result) {
            grd.flexReload();                    
            alert('saved.');
        }
    });

基本原理在此处找到:http://forum.jquery.com/topic/jquery-1-4-breaks-asp-net-mvc-parameter-posting

答案 1 :(得分:0)

您无法将JSON绑定到开箱即用的方法参数。 See here for a solution使用ValueProviders。