Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Model Binding a Collection With a Prefix

Tags:

asp.net-mvc

I want to bind a collection using a prefix, like so

public ActionResult Whatever([Bind(Prefix = "Prefix")] CustomModel[] models)

I created form elements using

<%= Html.TextBox("Prefix.models[" + i + "].Property") %>

which generated html inputs like this

<input id="Prefix_models[0]_Property" name="Prefix.models[0].Property" />

My problem is that the default model binder will not bind with a prefix. I get null for the models arg in the action method.

If I strip the prefixes from the html and remove the Bind attribute, everything works fine. I cannot imagine that the default model binder won't handle a prefix on a collection, so I must be doing something wrong.

Please help. Cheers!

like image 979
spot Avatar asked Feb 23 '10 15:02

spot


2 Answers

Prefix inside of [Bind] isn't prepended to the parameter name, it replaces the parameter name entirely. So if your action method has this signature:

public ActionResult MyAction([Bind(Prefix = "foo")] string[] bar) { ... }

The the binder expects foo[0], foo[1], etc.

like image 92
Levi Avatar answered Oct 08 '22 01:10

Levi


UpdateModel() and TryUpdateModel() take a parameter for prefix. Have you tried that?

like image 1
bkaid Avatar answered Oct 07 '22 23:10

bkaid