ASP.NET MVC - get list of objects from query string

后端 未结 5 937
鱼传尺愫
鱼传尺愫 2020-12-19 11:25

I\'m passed a list of parameters. Such as \"Name\", \"Id\", \"Type\". There will be an many of these in url, like so:

\"Name=blah1,Id=231,Type=blah1;Name=         


        
5条回答
  •  粉色の甜心
    2020-12-19 12:09

    Yes, ASP.NET MVC could automatically bind collections to action params, but you need to pass your params as a from values, moreover, it is looks like to many params you going pass in query string. Have look at this one http://weblogs.asp.net/nmarun/archive/2010/03/13/asp-net-mvc-2-model-binding-for-a-collection.aspx

    Basically what you need to do:

    1) Create your class which would contain your params

    public class MyParam 
    {
     public int Id {get; set;}
     public string Name {get; set;}
    
     //do all the rest
    }
    

    2) Create model which you would pass to your view

    public class MyViewModel
    {
      IList MyParams {get; set;}
    }
    

    3) Create your collection in your [HttpGet] action and pass that to your view:

    [HttpGet]
    public virtual ActionResult Index()
    {
       MyViewModel model = new MyViewModel();
       model.MyParams = CreateMyParamsCollection();
    
       return View(model);
    }
    

    4) Iterate your collection in the view

    @model MyViewModel
    
    @{int index = 0;}
    
    @foreach (MyParam detail in Model.MyParams)
    {
      @Html.TextBox("MyParams[" + index.ToString() + "].Id", detail.Id)
      @Html.TextBox("MyParams[" + index.ToString() + "].Name", detail.Name)
    
      index++;
    } 
    

    5) Than on your [HttpPost] action you may catch your params in collection

    [HttpPost]
    public virtual ActionResult Index(MyViewModel model)
    

    or

    [HttpPost]
    public virtual ActionResult Index(IList model)
    

    P.S

    Moreover, if you want to get all your form params in controller you may simple go like that:

    [HttpPost]    
    public virtual ActionResult Index(FormCollection form)
    

提交回复
热议问题