开发者

Model Binding to IDictionary<int, IList<int>> in ASP.Net MVC 2.0

I'm stuck !!!

Kindly help me out.

I have following view model property in my mvc 2.0 project...

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

Basically I have group of checkboxes under one or more tabs. These tabs are like English, German, French etc. etc.. I want to use tabId as dictionary Key and selected checkbox IDs as Dictionary Value (Integer List). I can't seem to bind my model that way. I previously found on stackoverflow that to map to Dictionary Key, we need an hidden field e.g.

<input type="hi开发者_Python百科dden" name="<%: String.Format("SelectedErrorsErrorType[{0}].Key", index) %>"value="<%: item.LanguageId %>" />

That's Fine ! But how do I map Value field against my Key.

Any help would be highly appreciated.

Thanks.


This was quite easy.. don't know why I couldn't figure this out in the first place.

Here's how it worked for me...

<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 })%>


Seems like here is the solution: ASP.NET MVC - Model binding a set of dynamically generated checkboxes - how to

But you can also use

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 */ }
   }
}

and bind to PostedValues.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜