Search code examples
c#.netasp.net-mvc-4razorformcollection

.Net MVC 4 How to get array in Model or from Form Collection on form submit


I am working with .net MVC 4 my problem is I have multiple input control with same name with postfix 0,1,2 like array. I want all of those values in one object or list of object. Controls in my View(Razor,.cshtml) is like below:

<input type="hidden" value="FirstName" name="MyListData[0]" id="MyListDataUnSelected_0_">
<input type="hidden" value="MiddleName" name="MyListData[1]" id="MyListDataUnSelected_1_">
<input type="hidden" value="LastName" name="MyListData[2]" id="MyListDataUnSelected_2_">

and my post method on controller is like:

public ActionResult Index(List<string> MyListData, FormCollection pFormCollection)

in from collection it gives me value of MyListData[0],MyListData[1],... but List MyListData is null. I have one other Page in that same code is applied and in that case I get list of values in MyListData.

I also tried using string[] MyListData but still not work.

How can I get that list in model or from Form Collection.


Solution

  • My current solution is

    List<string> lststr=new List<string>();
    int i=0;
    while(true)
    {
        if(pFormCollection["MyListData[" + i + "]"]!=null)
        {
             lststr.add(pFormCollection["MyListData[" + i + "]"]);
             i++;
        }
        else
            break;
    }
    

    or in short

    List<string> lststr=new List<string>();
    int i=0;
    while(pFormCollection["MyListData[" + i + "]"]!=null)
    {
    
             lststr.add(pFormCollection["MyListData[" + i + "]"]);
             i++;
    
    }