crunchy
crunchy

Reputation: 703

Can't get value from @Html.RadioButtonFor with complex types

I have a list of objects each of which have nested lists, which each have a date property. I need to be able to select one of these dates.

The model looks like this

public class ViewModel 
{
    public IList<ParentClass> ParentClasses {get;set;}
}

public class ParentClass
{
    public IList<DateSelector> DateSelectors {get;set;}     
    public DateTime SelectedDate {get;set;}
}

public class DateSelector
{
    public DateTime Date {get;set;}
}

In the view for the select action:

@using (Html.BeginForm())
{
    for(int i = 0; i < @Model.ParentClasses.Count; i++)
    {
        for(int j = 0; j < @Model.ParentClasses[i].DateSelectors.Count; j++)
        {
            @Html.RadioButtonFor(m => m.ParentClasses[i],
                Model.ParentClasses[i].DateSelectors[j].Date,
                new { @id = Model.ParentClasses[i].DateSelectors[j].Date.ToString("MMddyyyy") })

            @Model.ParentClasses[i].DateSelectors[j].Date.ToShortDateString()

            <br/>
        }
        <button type="submit">Submit</button>
    }

}

The view renders as I expect, but I can't get a value for the selected date. The html renders like

<form method="post" action="/Date/SelectDate">

    <input id="04272014" type="radio" value="4/27/2014 12:00:00 AM" name="ParentClasses[0]"></input>

    4/27/2014            

    <br></br>
    <input id="11012014" type="radio" value="11/1/2014 12:00:00 AM" name="ParentClasses[0]"></input>

    11/1/2014            

    <br></br>
    <button type="submit">

        Submit

    </button>

</form>

I'd really appreciate any insights here, I'm already a couple of days behind on this project.

Thanks

Upvotes: 0

Views: 146

Answers (1)

Matt Klinker
Matt Klinker

Reputation: 773

It's been a while since using Razor, but I believe your inital lambda for property selector on the Html.RadioButtonFor is wrong. You are attempting to bind that control the value of the ParentClass instance itself rather than ParentClass.SelectedDate. I believe if you change to:

@Html.RadioButtonFor(m => m.ParentClasses[i].SelectedDate,
Model.ParentClasses[i].DateSelectors[j].Date,
new { @id = Model.ParentClasses[i].DateSelectors[j].Date.ToString("MMddyyyy") })

That might work out for you, if it still does not work post back and I'll see about working up a sample.

Upvotes: 1

Related Questions