views:

38

answers:

2

Hi All

I have a view that contains 2 list boxes: Audience & Locale

I'm trying to submit a form that contains the selected index of both to my controller, which has an action method of this signature:

public JsonResult Submit(Audience aud, Locale loc)
{
// do stuff
}

The problem I'm having is both Audience & Locale have an ID property, so the Model Binder is a little bit confused over which to assign the selected values to. Both get assigned the value '1', when Audience should have '2' and Locale should have '1'

The question is how can I get the page to differentiate between the two when it's submitting? We've tried prepending the ID value for Locale with "locale.", so the parameter string that gets passed as data to the Controller looks like "&locale.id=1&audience.id=2" but that doesn't seem to work.

Any suggestions? If more info is needed, I'll supply it.

Thanks

Dave

+1  A: 

You should have a specific ViewModel for taking data into your Submit Action. That object should have AudienceId and LocaleId. When you create your dropdowns you should create them with names that match what you expect.

Keith Rousseau
+1  A: 

Use:

public JsonResult Submit([Bind(Prefix = "audience")]Audience aud,[Bind(Prefix = "locale")]Locale loc)
{
// do stuff
}

Every Audience field should have "audience" prefix in name in html field: audience.id,audience.name,...

<input id="audience_name" name="audience.Name" type="text" value="" />
LukLed
Yep this sound like the way to go, another option will be to use a single ViewModel and inside put the two Entity classes (like Keith said), so it ll be MyViewModel.Audience and MyViewModel.Locale following the name convention for the input element that Luk mention before.
Omar
In your example you're explicitely specifying the prefix. I thought the Model Binder could infer that?
DaveDev
@Dave: AFAIK it doesn't infer, but this could have changed between MVC versions. It would propably infer if you used ViewModel class.
LukLed
@Omar - I didn't mean to put the full Entity on the ViewModel. Entities should never be in your ViewModel - you should have the Ids and then map to the Entities.
Keith Rousseau
@Keith - You are right, but all depends on the scenario (sometimes you end up creating View Models that are almost the same as the Entity classes), i ll never save the MYViewModel.Audience object directly before doing some validation and take care of possible tampering with the data, CSRF´s, using Bind-Exclude and even some HMAC, if you correctly take care of those you should have no problems at all.
Omar