如何在MVC中实现视图以在模型中呈现Dictionary并将字典映射回模型

aga*_*ian 8 c# asp.net-mvc-3

假设你有这个模型:

//model 
public class Stuff
{
  public string Name { get; set; }
  public Dictionary<String, String> Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够创建一个动作及其相应的视图,以便用户可以在表单中添加Stuff对象的Name,并可以添加多个Description条目.

在这种特殊情况下,我希望密钥是一个语言代码,如'en','de','fr','es'等,以及描述给定语言的相应描述.

例如,在视图中,您可能会看到如下内容:

@model Stuff

@using(Html.BeginForm())
{
   <div>
       @Html.LabelFor(x=>x.Name)
       @Html.TextBoxFor(x=>x.Name)
   </div>
   <div>
        <!-- What goes in here to map to the Dictionary in the Stuff Model? -->
        <input name="LanguageCode" value="en" />  <input name="DescriptionValue" />
        <input name="LanguageCode" value="de" />  <input name="DescriptionValue" />
        <input name="LanguageCode" value="fr" />  <input name="DescriptionValue" />
   </div>
   <div>
        <input type="submit" value="save" />
   </div>
}


// controller

[HttpGet]
public ActionResult Index ()
{
  return View(new Stuff());
}

[HttpPost]
public ActionResult Index (Stuff myStuff)
{
  foreach(KeyValuePair kvp in myStuff.Description)
  {
       Trace.WriteLine(String.Format("Language: {0} - Description: {1}", kvp.Key, kvp.Value)); 
  }
  DBHelper.Save(myStuff);
  return View();
}
Run Code Online (Sandbox Code Playgroud)

接受任何替代解决方案.

谢谢.

Pau*_*sey 14

它将是这样的:

@int i = 0;
@foreach (var item in Model.Description) {
    <input name="Description[@i].Key" value="@item.Key" />  
    <input name="Description[@i].Value" value="@item.Value" />  
    @i++
}
Run Code Online (Sandbox Code Playgroud)

请参阅Scott Hanselman的这篇文章


lon*_*ero 5

您可以为Dictionary类型创建编辑器模板(和显示模板).然后,MVC将能够在模型中呈现字典实例.

例如,在您的模型中,您可以指定要使用的模板,如下所示:

public class Stuff
{
  public string Name { get; set; }

  [UIHint("Stringdictionary")]
  public Dictionary<String, String> Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在您的视图中,您必须这样做:

@model Stuff

@using(Html.BeginForm())
{
   <div>
       @Html.LabelFor(x=>x.Name)
       @Html.TextBoxFor(x=>x.Name)
   </div>
   <div>
       @Html.Editor(x=>x.Description )
   </div>
   <div>
        <input type="submit" value="save" />
   </div>
}
Run Code Online (Sandbox Code Playgroud)

而且,编辑器模板(你必须在Views/Shared/EditorTemplates文件夹中创建它)可能是这样的:

@model Dictionary<string,string>
@foreach (var item in Model) {
    @Html.EditorFor(x=>x.Key)
    @Html.EditorFor(x=>x.Value)
}
Run Code Online (Sandbox Code Playgroud)