2013-02-28 71 views
2

我嘗試訪問c#中的關聯數組。數組發送到我的c#mvc web應用程序的每個帖子。formcollection如何訪問html表單關聯數組

e。 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 

    ... 
    } 

我希望你能跟着我: -/

回答

0

當然可以;但您需要指定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"); 
} 
+1

對不起,這個問題是不是職位。我不知道如何訪問c#中的數據! – Dominik 2013-02-28 12:25:11

+0

好吧,我已經更新了我的答案以顯示如何。 – 2013-02-28 13:01:53

+1

謝謝。對不起,但我不知道的hashKey1,hasKey2,hashKeyN - 但我也需要密鑰,... – Dominik 2013-02-28 13:39:42

相關問題