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

2
  • What does the controller look like? Commented Mar 10, 2016 at 13:32
  • 1
    State is a complex object and a <select> posts back a single value, not a complex object. It would need to be @Html.DropDownListFor(m => m.JobSeeker.CurrentAddress.State.ID, ....) But do not do that!. Add a public Guid SelectedStata { get; set; } property to RegisterVM and bind to that. Commented Mar 10, 2016 at 21:49

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Based on OP's State class, it would need to be public Guid SelectedState { get; set; }
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...

Comments

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.