代码之家  ›  专栏  ›  技术社区  ›  Patricia

asp.net mvc model binder是否会以正确的顺序保留已发布的数组?

  •  2
  • Patricia  · 技术社区  · 15 年前

    所以我有一个数字数组,我发布到一个asp.NETMVC操作中,这个操作有一个list(整型)参数,一切都很好。

    可以安全地假设列表(整数)中的数字与我发布的数组中的数字顺序相同吗?

    编辑:

    正在发布的数据如下所示:

    POSTDATA=model.LevelIds=6&model.LevelIds=19&model.LevelIds=16&model.LevelIds=21&model.LevelIds=18

    我使用jQuery,在传统模式下。

    动作如下所示:

    public function Create(byval model as thecreateviewmodel) as actionresult
    

    CreateViewModel有很多属性,但有趣的是。。。

    Public Property LevelIdsAs IList(Of Integer) = New List(Of Integer)
    

    function NewEntityDataBuilder() {
        var theData = { 
            'model.Name' : $('#Name').val(),
            'model.Description' : $('#Description').val(),
            'model.LevelIds' : $('#LevelIds').val()
        };
        return theData;
    }
    

    这个函数是从javascript的这一部分调用的,javascript基本上通过,并将列表中的所有内容添加到下拉列表(select control)中,然后将它们全部选中。

    $('#LevelIds').empty();
    $('#AddedLevels').children().each(function () {
    $('#LevelIds').append("<option value='" + $(this).attr('LevelId') + "'>" + $(this).attr('LevelId') + "</option>");
            });
    
    $('#LevelIds').children().attr('selected', 'selected');  //select all the options so they get posted.
    
    var dataToPost = NewEntityDataBuilder();   
    

    所以:如果我把一个select列表的值和它的所有选项都选在一个变量中,并将其发布到一个ilist(整数)中,那么ilist将以与select中相同的顺序显示它们。好像是的。但这只是巧合吗?

    1 回复  |  直到 15 年前
        1
  •  0
  •   Darin Dimitrov    15 年前

    通常索引是参数名称的一部分:

    ints[0]=0&ints[2]=2&ints[1]=1
    

    如果控制器动作如下所示:

    public ActionResult Index(List<int> ints)
    {
        // ints[0] = 0
        // ints[1] = 1
        // ints[2] = 2
        return View();
    }
    

    假设查询字符串中有多个同名参数。此查询字符串将由ASP.NET引擎通过本机 HttpRequest 将对象转换为 NameValueCollection 更确切地说,是一个自定义实现,称为 HttpValueCollection FillFromString 而它的实施方式似乎维护了秩序。但这是我不能依赖的。