【问题标题】:Model Binding to IDictionary<int, IList<int>> in ASP.Net MVC 2.0在 ASP.Net MVC 2.0 中模型绑定到 IDictionary<int, IList<int>>
【发布时间】:2010-07-05 21:56:48
【问题描述】:

我卡住了!!!

请帮帮我。

我的 mvc 2.0 项目中有以下视图模型属性...

public IDictionary<int, IList<int>> SelectedErrorsErrorType { get; set; }

基本上我在一个或多个选项卡下有一组复选框。这些选项卡就像英语、德语、法语等。我想使用 tabId 作为字典键,并选择复选框 ID 作为字典值(整数列表)。我似乎无法那样绑定我的模型。我之前在 stackoverflow 上发现要映射到 Dictionary Key,我们需要一个隐藏字段,例如

<input type="hidden" name="<%: String.Format("SelectedErrorsErrorType[{0}].Key", index) %>"value="<%: item.LanguageId %>" />

没关系!但是如何将 Value 字段映射到我的 Key。

任何帮助将不胜感激。

谢谢。

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    这很容易..不知道为什么我一开始就想不通。

    这对我来说是这样的......

    <input type="hidden" name="<%: String.Format("SelectedErrorsErrorType[{0}].Key", index) %>"
                                                                value="<%: item.LanguageId %>" />
    
    <%: Html.CheckBox(String.Format("SelectedErrorsErrorType[{0}].Value[{1}]", index, counter), false, new { @value = errorType.ErrorTypeId })%>
    

    【讨论】:

    • 你需要把这个放到你的帖子里,而不是一个新帖子里!
    • Ohhkk ...下次会小心的,伙计!
    【解决方案2】:

    似乎这是解决方案:ASP.NET MVC - Model binding a set of dynamically generated checkboxes - how to

    但你也可以使用

    public class ErrorType
    {
       public int Key { get; set; }
       public int Value { get; set; }
    }
    
    public class ViewModel
    {
       public IList<ErrorType> PostedValues { get; set; }
    
       public IDictionary<int, IList<int>> SelectedErrorsErrorType 
       { 
         get { return PostedValues.GroupBy(x => x.Key).ToDictionary(x => x.Key, x => x.Select(y => y.Value).ToList());
         set { /* backward if you need it */ }
       }
    }
    

    并绑定到 PostedValues。

    【讨论】:

    • 嘿,谢谢你的努力,伙计!我也会尝试你的解决方案:)
    猜你喜欢
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    相关资源
    最近更新 更多