【问题标题】:Dictionary<,> Binding to a Controller in Asp.Net MVCDictionary<,> 在 Asp.Net MVC 中绑定到控制器
【发布时间】:2015-03-11 22:53:31
【问题描述】:

我有一个如下所示的课程。

   public class ProductViewGridModel
    {
        public long Id { get; set; }
        public string PackageCode { get; set; }
        public string ProductName { get; set; }
        public string ProductCategory { get; set; }
        public IDictionary<string, string> Localizations { get; set; }

    }

我将模型渲染成这样查看。(foreach 语句运行到表中,我不在这里显示它。)

 @foreach (var localization in Model.Localizations)
                {
                    var p = localization.Value;
                    <tr>
                        <td class="adminData">
                            <input class="k-textbox" type="text" value="@p" name="productView.Localizations[@localization.Key]" />
                            <input type="hidden" value="@p" name="productView.Localizations[@localization.Key]" />
                        </td>
                    </tr>
                }

我有一个按钮,该按钮通过 ajax 调用向控制器发送表单值。

其他模型绑定没问题,但我想将所有本地化输入绑定到本地化模型。 但是本地化总是无效的。我该如何绑定这个?。

【问题讨论】:

  • 名字不对,只能是Localizations[@localization.Key]
  • 你是个了不起的人 :) 我差点写 Defaultvaluebinder,你救了我 :)
  • 您可以将所有这些简化为 foreach (var key in Model.Localizations.Keys) { @Html.TextBoxFor(m =&gt; m.Localizations[key]) }(添加隐藏输入没有意义 - 它只是创建无效的 html 并且模型绑定器无论如何都会忽略它)
  • @StephenMuecke 是的,您的解决方案是正确的,感谢您的建议。

标签: c# asp.net-mvc-4 razor reflection


【解决方案1】:

输入名称错误。默认的modelbinder 会寻找属性Localizations

@foreach (var localization in Model.Localizations)
{
    var p = localization.Value;
    <tr>
        <td class="adminData">
            <input class="k-textbox" type="text" value="@p" name="Localizations[@localization.Key]" />
            <input type="hidden" value="@p" name="Localizations[@localization.Key]" />
        </td>
    </tr>
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多