简体   繁体   English

ASP.NET MVC:操作方法,并自动绑定到值数组

[英]ASP.NET MVC: Action Method and automatically binding to an array of values

I have a piece of javascript that posts to an action method, and with it some data. 我有一段JavaScript,可以发布到一个操作方法中,并附带一些数据。 This data is in the form: 该数据的格式为:

pageID  1
photos[1]   2
photos[2]   1

My Action Method looks as follows: 我的操作方法如下所示:

public ActionResult PosImage(IEnumerable<int> photos, int pageID)

Naturally, pageID comes through in the form data, but photos is always null. 自然,pageID通过表单数据进入,但是照片始终为空。

Is it possible for ASP.MVC to bind like this? ASP.MVC是否可以像这样进行绑定?

The JS that handles the post looks as follows: 处理该帖子的JS如下所示:

var ids = { 'photos': {}, 'pageID': SitePhotos.site_id };
    $('#stone-photo-sortable li').each(function (i) {
        i++;
        var id = $(this).attr('rel');
        ids.photos[id] = i;
    });
    $.ajax({
        type: "POST",
        url: '/backend/site/posimage/?timestamp=' + new Date().getTime(),
        dataType: 'json',
        data: ids,
        beforeSend: function () { },
        complete: function () { },
        success: function (html) {
            if (html.worked == 1) {
                Notify.add('success', 'New Positions saved to the database..');
            } else {
                Notify.add('failure', 'Couldn\'t save positions.');
            }

        }
    });

I havent done it from javascript, but your post data should actually be like this: 我还没有用javascript完成它,但是您的发布数据实际上应该是这样的:

photos: 1
photos: 2
photos: 3

You probably need to use a different $.ajax overload inorder to pass post data with duplicate key names. 您可能需要使用其他$ .ajax重载才能传递具有重复键名的帖子数据。

edit seems like all you have to do is to set traditional flag to true. 编辑似乎要做的就是将传统标志设置为true。

It seems to me this would work better for you if you turn the photos object around and making it into an array instead like this: 在我看来,如果您将photos对象转过来并将其变成一个数组,则对您来说会更好:

var ids = { 'photos': [], 'pageID': SitePhotos.site_id };
    $('#stone-photo-sortable li').each(function (i) {
        ids.photos[i] = $(this).attr('rel');
    });

Sergio, this can be fixed very easy. Sergio,这可以很容易地解决。

IEnumerable<int> photos will work, but your array should always start at 0 ! IEnumerable<int> photos可以使用,但您的数组应始终从0开始! not at 1 不等于1

make it start at 0 and MVC will parse it into your IEnumerable 使其从0开始,MVC会将其解析为IEnumerable

read more about it here: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx 在这里阅读更多关于它的信息: http : //haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM