Binding Viewmodel Property to dropdown selected item in razor

守給你的承諾、 提交于 2019-12-11 11:13:07

问题


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


回答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.




回答2:


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...




回答3:


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 .



来源:https://stackoverflow.com/questions/35917916/binding-viewmodel-property-to-dropdown-selected-item-in-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!