从隐藏字段获取字典 <string, string> 的值到 asp.net mvc 中的 post 方法

Get value of dictionary<string, string> from hidden field to post method in asp.net mvc

我正在创建一个 Web 应用程序,我需要在其中获取 post 方法

public Dictionary<string, string> KeyValuePairs { get; set; } 的值

这是我的代码的样子,

我的模型 -> public Dictionary<string, string> KeyValuePairs { get; set; }

以上属性已包含在我的模型中

@{
    var index = 0;
    foreach (var item in Model.KeyValuePairs)
    {
        <input type="hidden" value="@item.Key" name="@Model.KeyValuePairs.ElementAt(index).Key" />
        <input type="hidden" value="@item.Value" name="@Model.KeyValuePairs.ElementAt(index).Value" id="@index" />
        index++;
    }
}

我正在存储 Dictionary<string, string> 的所有键值,但在我的控制器 post 事件中仍显示为空,

我也试过如下

@foreach (KeyValuePair<string, string> kvp in Model.KeyValuePairs)
{
    <input type="hidden" name="KeyValuePairs[@index].key" value="@kvp.Key" />
    <input type="hidden" name="KeyValuePairs[@index].Value" value="@kvp.Value" />
    index++;
}

我需要做什么才能在 Post

中获取词典

实际上name="@Model.KeyValuePairs.ElementAt(index).Key"正在获取值。它应该是 name="Model.KeyValuePairs[@index].Key" 然后它将数据绑定到模型。

查看我下面的代码可以更清楚地理解。

型号

public class KeyValuePairs {
     public Dictionary<string, string> DictList { get; set; }
}

控制器

[HttpPost]
public ActionResult PassDictionary(KeyValuePairs model)
{
    return RedirectToAction("PassDictionary");
}

查看

@model Project.Web.Models.KeyValuePairs

@using (Html.BeginForm("PassDictionary", "ControllerName", FormMethod.Post, new { })) {

    // I have changed foreach to forloop so no need to declare index 
    for (int i = 0; i < Model.DictList.Count; i++) {

    <input type="hidden" value="@Model.DictList.ElementAt(i).Key" name="Model.DictList[@i].Key" />
    <input type="hidden" value="@Model.DictList.ElementAt(i).Value" name="Model.DictList[@i].Value" />

   }
   <button type="submit" value="Submit">Submit</button>
}