gpt4 book ai didi

c# - formcollection如何访问html表单关联数组

转载 作者:太空宇宙 更新时间:2023-11-03 16:17:56 25 4
gpt4 key购买 nike

我尝试访问 C# 中的关联数组。该数组按帖子发送到我的 c# mvc web 应用程序。

G。 html 表单

 <Input Name="myArray[hashKey1]" value="123">
<Input Name="myArray[hashKey2]" value="456">

在 C# 中,我需要键和值——可能需要数据字典?!

    [HttpPost]
public ActionResult Index(FormCollection collection)
{
Dictionary<string, string> = KEY, VALUE

...
}

我希望你能关注我:-/

最佳答案

是的,你可以;但是你需要指定POST的方法。

这行不通:

<form id="frmThing" action="@Url.Action("Gah", "Home")">
<input id="input_a" name="myArray[hashKey1]" value="123" />
<input id="input_b" name="myArray[hashKey2]" value="456" />

<input type="submit" value="Submit!"/>
</form>

这样做:

<form id="frmThing" action="@Url.Action("Gah", "Home")" method="POST">
<input id="input_a" name="myArray[hashKey1]" value="123" />
<input id="input_b" name="myArray[hashKey2]" value="456" />

<input type="submit" value="Submit!"/>
</form>

编辑:要实际访问 C# 中的详细信息,在您的示例中,您将执行以下操作之一:

String first = collection[0];
String secnd = collection[1];

String first = collection["myArray[hashKey1]"];
String secnd = collection["myArray[hashKey2]"];

甚至:

foreach (var item in collection) {
string test = (string)item;
}

编辑二:

这里有一个技巧,您可以使用它来获得您想要看到的行为。首先,定义一个扩展方法:

public static class ExtensionMethods
{
public static IEnumerable<KeyValuePair<string, string>> Each(this FormCollection collection)
{
foreach (string key in collection.AllKeys)
{
yield return new KeyValuePair<string, string>(key, collection[key]);
}
}
}

然后在您的操作结果中您可以这样做:

public ActionResult Gah(FormCollection vals)
{
foreach (var pair in vals.Each())
{
string key = pair.Key;
string val = pair.Value;
}

return View("Index");
}

关于c# - formcollection如何访问html表单关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15132450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com