1
public class State
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}
public class Address
{

    public State State { get; set; }

}

public class JobSeeker
{

    public Address CurrentAddress { get; set; }


}

public class RegisterVM
{
    public JobSeeker JobSeeker { get; set; }
    public List<State> AllStates { get; set; }
}

in Razor

 @Html.DropDownListFor(m => m.JobSeeker.CurrentAddress.State, 
              new SelectList(Model.AllStates, "Id", "Name" ), "  -----Select List-----  ")

The result is the drop down is populated with the value present in AllStates, but the problem is m.JobSeeker.CurrentAddress.State is null when posted to controller action. How to set the selected value of dropdown to property m.JobSeeker.CurrentAddress.State

tereško
  • 58,060
  • 25
  • 98
  • 150
Pankaj kumar jha
  • 133
  • 2
  • 13
  • What does the controller look like? – Christian Phillips Mar 10 '16 at 13:32
  • 1
    `State` is a complex object and a ` –  Mar 10 '16 at 21:49

3 Answers3

1

If you change the ViewModel to...

public class RegisterVM
{
    public JobSeeker JobSeeker { get; set; }
    public List<State> AllStates { get; set; }
    public string SelectedState { get; set; }
}

..and have the Drop down use the SelectedState property instead...

@Html.DropDownListFor(m => m.SelectedState, 
              new SelectList(Model.AllStates, "Id", "Name" ), "  -----Select List-----  ")

You should then be able to assign it to the State by name.

Christian Phillips
  • 18,399
  • 8
  • 53
  • 82
  • Based on OP's `State` class, it would need to be `public Guid SelectedState { get; set; }` –  Mar 10 '16 at 21:50
0

How is the model binder supposed to map an Id of the state to the model of type State??? If you change your razor view code to:

@Html.DropDownListFor(m => m.JobSeeker.CurrentAddress.State.Id, new SelectList(Model.AllStates, "Id", "Name" ), "--Select--")

Then you will get a non-null instance of state but only the Id property will be populated...

Marko
  • 12,543
  • 10
  • 48
  • 58
0

Thanks all of you. I was able to figure out the problem after viewing the Request.Form object which has only one value against State Field i.e SelectedValue of dropdownlist. As far I understand, it is not possible to set the state property from UI hence I have to use the selected ID of State received from view in the ModelBinder or Controller to set the State Object from db .

Pankaj kumar jha
  • 133
  • 2
  • 13