Carl R
Carl R

Reputation: 8214

Lists as mvc controller method arguments?

I have 2 tables containing checkboxes in a MVC form. The names of the checkboxes are currently more or less random. Can I name the items in any smart way so that I can retrieve them as two named lists as controller method arguments? Preferably if I could do with prefixing the names.

<div>
    <input type="checkbox" name="xyz" />
    <input type="checkbox" name="foo" />
    <input type="checkbox" name="123" />
</div>

<div>
    <input type="checkbox" name="bar" />
    <input type="checkbox" name="456" />
    <input type="checkbox" name="baz" />
</div>

Can I somehow get it as arguments, similar to this?

public ActionResult DoThis(BlablahViewModel model, string[] firstList, string[] secondList)
{

Currently I just check for their existence roughly like this:

Request.Form["xyz"].Contains("t")

Thanks!

Upvotes: 1

Views: 3860

Answers (1)

John Farrell
John Farrell

Reputation: 24754

You'll need to use the List Model Binding features of MVC:

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

For a good guide of how this can all work together:

http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/

Upvotes: 2

Related Questions