views:

29

answers:

1

I have a question regarding Model Binding in MVC

Say I have a simple POCO like below.

public class Person
{
    public Title Title { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool LeadPassenger { get; set; }
}

I have a controller that passes a collection of Persons to a View and within that View I want to render a radio button to allow the user to select the LeadPassenger from the collection of Persons.

Now, for this to work (and only one radio button be selected at a time) all the "LeadPassenger" radio buttons must share the same name. But this seems to be impossible using the Model Binding conventions whereby each control is named after each property of the item in the collection.

<input id="Passengers_0_LeadPassenger " name="PolicyMembers[0].LeadPassenger" type="radio" value="true" />
<input id="Passengers_1_LeadPassenger " name="PolicyMembers[1].LeadPassenger" type="radio" value="false" />

How do I get round this limitation? I could use jQuery to force all the radio buttons to switch off when one is selected but that seems to be a 'fudge'!

Any ideas?

A: 

The trick here is the task you are trying to accomplish isn't really something for model binding, which isn't really aware of data outside it's "row" so to speak. What you want to do here is introduce a new field for lead passenger selection, binding the value to the unique identifier for person and the name to the same thing. Then pick it up as a separate variable in your controller and map it from there.

Wyatt Barnett