如何将多选下拉列表绑定到asp.net控制器动作参数

时间:2011-02-21 21:29:37

标签: asp.net-mvc select model-binding fcbkcomplete

我有一个html表单,发布到asp.net-mvc控制器操作,之前工作正常。我刚刚添加了一个新的多选下拉列表(使用fcbkcomplete jquery插件),我遇到了将它绑定到我刚刚添加了我的绑定对象的新属性的问题

我刚刚上市:

 <select id="SponsorIds" name="SponsorIds"></select>

在html中,但看起来fcbkcomplete以某种方式将其更改为name =“SponsorIds []”。

这是我在浏览器中显示“选定来源”后得到的HTML。

<select multiple="multiple" style="display: none;" id="SponsorIds" name="SponsorIds[]">

这里是从插件中吐出的所有html

 <select multiple="multiple" style="display: none;" id="SponsorIds" name="SponsorIds[]">
<option class="selected" selected="selected" value="9">MVal</option>
</select>
<ul class="holder">
<li rel="9" class="bit-box">MVal<a href="#" class="closebutton"></a></li>
<li id="SponsorIds_annoninput" class="bit-input"><input size="1" class="maininput"    type="text"></li>
</ul>
<div style="display: none;" class="facebook-auto">
<ul style="width: 512px; display: none; height: auto;" id="SponsorIds_feed">
<li class="auto-focus" rel="9"><em>MVal</li></ul><div style="display: block;" class="default">Type Name . . .
</div>
</div>

这是我的控制器动作:

 public ActionResult UpdateMe(ProjectViewModel entity)
    {
    }

视图模型,ProjectViewModel有一个属性:

   public int[] SponsorIds { get; set; }

我认为它可以很好地绑定到这个但似乎并不像它在服务器端显示为“null”。谁能在这里看到任何错误?

1 个答案:

答案 0 :(得分:2)

正确命名的列表框(就默认的ASP.NET MVC模型绑定器可以处理的内容而言)将是:

name="SponsorIds"

而不是:

name="SponsorIds[]"

至少如果您希望使用默认的模型绑定器将其绑定回int[]。这就是Html.ListBoxFor助手生成的内容。例如:

@Html.ListBoxFor(
    x => x.SponsorIds, 
    new SelectList(
        new[] { 
            new { Value = "1", Text = "MVal1" },
            new { Value = "2", Text = "MVal2" }, 
            new { Value = "3", Text = "MVal3" }, 
        }, 
        "Value", "Text"
    )
)

发射:

<select id="SponsorIds" multiple="multiple" name="SponsorIds">
    <option value="1">MVal1</option>
    <option value="2">MVal2</option>
    <option value="3">MVal3</option>
</select>

并且模型活页夹很高兴。


更新:

你也可以有一个能够解析它的自定义模型绑定器:

public class FCBKCompleteIntegerArrayModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[]");
        if (values != null && !string.IsNullOrEmpty(values.AttemptedValue))
        {
            // TODO: A minimum of error handling would be nice here
            return values.AttemptedValue.Split(',').Select(x => int.Parse(x)).ToArray();
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}

然后在Application_Start注册此活页夹:

protected void Application_Start()
{
    ...
    ModelBinders.Binders.Add(typeof(int[]), new FCBKCompleteIntegerArrayModelBinder());
}