0

asp.net-mvc コントローラー アクションに投稿する html フォームがあり、以前は正常に動作していました。(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」として表示されるだけなので、そうではないようです。誰かがここで何か間違ったことを見ることができますか?

4

1 に答える 1

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());
}
于 2011-02-21T21:38:46.000 に答える