简体   繁体   English

MVC DropDownListFor-选定值ViewModel类

[英]MVC DropDownListFor - Selected Value ViewModel Class

I am trying populate the selected value of a dropdown list. 我正在尝试填充下拉列表的选定值。 When I set the selected value on my ViewModel as a string, it works perfectly. 当我在ViewModel上将所选值设置为字符串时,它可以完美工作。 When I set the selected value property as part of a subclass, it fails: 当我将选定的value属性设置为子类的一部分时,它将失败:

@Html.DropDownListFor(model => model.JMASettings.CustomerID, Model.CustomerIDList)

This method works: 此方法有效:

@Html.DropDownListFor(model => model.CustomerID, Model.CustomerIDList)
  1. Is it OK to have classes inside of the ViewModel? 在ViewModel中包含类可以吗?

     public class SettingsViewModel { public SettingsViewModel() { JMASettings = new JMASettings(); } public JMASettings JMASettings {get; set;} } public class JMASettings { public string CustomerID {get; set;} } 
  2. Do you recommend that I copy and paste the contents of JMASettings into my settings view model class? 您是否建议我将JMASettings的内容复制并粘贴到我的设置视图模型类中?

  1. Sure. 当然。 Your view model can contain whatever you like. 您的视图模型可以包含您喜欢的任何内容。

  2. Not necessarily. 不必要。 There's no functional reason your first attempt using model.JMASettings.CustomerID shouldn't show the selected value. model.JMASettings.CustomerID功能上的考虑,您首次尝试使用model.JMASettings.CustomerID不应显示所选值。 If it's not, then there's some other problem. 如果不是,则还有其他问题。 You may not be properly populating the CustomerID property on JMASettings instance, or something in ModelState may be overriding what you set. 您可能没有正确填充JMASettings实例上的CustomerID属性,或者ModelState某些内容可能会覆盖您设置的内容。 ModelState is composed of values from Request , ViewData and ViewBag , first , and only values from Model as a last resort. ModelStateRequestViewDataViewBag first值组成,最后一个由Model值组成。

Is it OK to have classes inside of the ViewModel? 在ViewModel中包含类可以吗?

Yes it is OK, but probably not necessary. 是的,可以,但是可能没有必要。

Do you recommend that I copy and paste the contents of JMASettings into my settings view model class? 您是否建议我将JMASettings的内容复制并粘贴到我的设置视图模型类中?

Yes I recommend to move it to a single model as the subclass will require you to create a custom model binder. 是的,我建议将其移至单个模型,因为子类将需要您创建自定义模型绑定器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM