【问题标题】:pass Dictionary<string, List<string>> from View to Controller in MVC将 Dictionary<string, List<string>> 从 View 传递到 MVC 中的控制器
【发布时间】:2017-05-09 22:31:22
【问题描述】:

我想将一些数据从我的视图传递给我的控制器,我的视图如下所示:

  <div id="Section1" class="divFiles">
    <span>Section 1 </span>

<input type="text" name="test[0]">

<input type="text" name="test[1]">

<input type="text" name="test[2]">

<input type="text" name="test[3]">

</div>

  <div id="Section2" class="divFiles">
    <span>Section 2 </span>

<input type="text" name="test[4]">

<input type="text" name="test[5]">

<input type="text" name="test[6]">

<input type="text" name="test[7]">

</div>

但是这样我只是向我的控制器发送一个字符串列表,没有键,我需要键,因为我需要按键分组。

我想像Dictionary 一样传递我的数据,按部分分组,例如:

Section 1: {"first string", "second string", "third string"}, Section 2: {"fourth string", "fifth string"}

就像那样,我认为最好的方法可能是将数据作为Dictionary&lt;string, List&lt;string&gt;&gt; 类型的Dictionary 发送,其中Section 1Section 2 将是keys,然后是他们values的字符串列表,我该怎么做?我也可以为此目的使用 JQuery,但我不确定我必须如何编写 html 来发送这样的数据。这样做我的控制器操作中的参数应该是 Dictionary&lt;string, List&lt;string&gt;&gt; 类型的任何以不同方式执行此操作的建议也欢迎

【问题讨论】:

  • 创建一个包含字符串数组和 name 属性的对象(用于部分)。然后创建一个包含一个或多个这些对象的数组。在 javascript 中执行此操作。然后在 c# 中创建一个类似的类。您的控制器应该采用一个数组或它们的列表。将其作为 json 发送到您的控制器。

标签: c# jquery html asp.net-mvc dictionary


【解决方案1】:

对于除了简单的Dictionary 之外的所有KeyValue 都是值类型(例如Dictionary&lt;string, int&gt;),DefaultModelBinder 要求控件名称采用以下格式(在您的情况下, 假设 POST 方法签名是public ActionResult XX(Dictionary&lt;string, List&lt;string&gt;&gt; names))

<input name="names[0].Key" value="aaa" ... />
<input name="names[0].Value[0]" value="bbb" ... />
<input name="names[0].Value[1]" value="ccc" ... />
<input name="names[1].Key" value="xxx" ... />
<input name="names[1].Value[0]" value="yyy" ... />
<input name="names[1].Value[1]" value="zzz" ... />

没有HtmlHelper 扩展方法可以为包含Key 和/或Value(这是一个复杂对象或集合)的Dictionary 生成正确的name 属性,这意味着您将需要手动生成所有 html 并失去强类型绑定、客户端验证等的所有好处。

例如,创建一个表示您的结构的视图模型会容易得多

public class ValueVM
{
    public string Name { get; set; }
}
public class GroupVM
{
    public string Key { get; set; }
    public List<ValueVM> Values { get; set; }
}

然后在GET方法中初始化一个GroupVM的集合,填充数据并传递给视图,例如

var model = new List<GroupVM>
{
    new GroupVM
    {
        Key = "Section 1",
        Values = new List<ValueVM>
        {
            new ValueVM { Name = "...." },
            new ValueVM { Name = "...." }
        }
    },
    new GroupVM
    {
        Key = "Section 2",
        ....
    }
};
return View(model);

然后在视图中

@model List<GroupVM>
....
@using (Html.BeginForm())
{
    @for(int i = 0; i < Model.Count; i++)
    {
        <div>
            <h2>@Model[i].Key</h2>
            @Html.HiddenFor(m => m[i].Key)
            @for (int j = 0; j < Model[i].Values.Count; j++)
            {
                @Html.TextBoxFor(m => m[i].Values[j].Name)
            }
        </div>
    }
    ....
}

POST 方法的签名是

public ActionResult XXXX(List<GroupVM> model)

【讨论】:

    【解决方案2】:

    您应该创建一个对象,然后将该对象传递给您的控制器。这会容易得多,否则您将拥有一个带有大量参数的控制器来执行表单提交。我会使用 JavaScript,然后简单地执行 Ajax 请求。

    public class Example
    {
         public int Id { get; set; }
         public string Key { get; set; } // Bad name
         public string Value { get; set; } // Bad name
    }
    

    所以你的控制器会期望,示例

    public IActionResult Submit(List<Example> examples)
    {
         // Collection of our inputs as an object, manipulate.
    }
    

    那么对于 JavaScript,您只需这样做:

    function getFormDataAndCreateObject() {
         var formElements = $('[data-rel="section"]');
         var elements = [];
    
         $.each(formElements, function (index) {
              elements.push(buildExample(index, formElements[index].attr('name'), formElements[index].value));
         });
    
         // Either return elements, or simply perform Ajax to send to controller.
    }
    
    function buildExample(id, section, name) {
         var examples = [{
              Id : id,
              Section: section,
              Name: name
         }];
    }
    

    可能有错别字,但概念才是最重要的。

    【讨论】:

      猜你喜欢
      • 2014-02-17
      • 2015-07-02
      • 1970-01-01
      • 2012-12-02
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多