如何在动态类型上使用 DropDownListFor()?
我在 DropDownListFor()
中收到以下错误“表达式树可能不包含动态操作”,因为 lambda 使用动态类型。
如何在不使用 jQuery 的情况下设置 DropDownList 上的选定选项?
我也不想制作模板或自定义助手。
模型
public class Thing : Base {
public virtual Nullable<int> OptionID { get; set; }
public virtual Option Option { get; set; }
}
public class Option : Base {
public virtual ICollection<Thing> Things { get; set; }
}
public class Base {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
控制器
public ActionResult Edit(int Id) {
return View(new ViewModel(context, new Thing()));
}
视图
@model MvcApp7.Models.ViewModel
@{
var Entity = (dynamic)Model.Entity;
}
@Html.DropDownListFor(x => Entity.OptionID , (System.Web.Mvc.SelectList)Model.Options)
ViewModel
public class ViewModel {
public ViewModel(Context context, object entity) {
this.Entity = entity;
this.Options = new SelectList(context.Options, "Id", "Name");
}
public dynamic Entity { get; set; }
public SelectList Options { get; set; }
}
编辑:请原谅。我忘记了我可以在 SelectList 本身中指定选定的选项。我将责任转移到 ViewModel 中,并将尝试从那里处理它。然而,如果有必要的话,最好知道如何在视图本身中解决这个问题。
我在 ViewModel 中这样做了this.Options = new SelectList(context.Options, "Id", "Name", this.Entity.OptionID);
这在视图中@Html.DropDownList("OptionID", Model.Options)
I get the following error in the DropDownListFor()
"An expression tree may not contain a dynamic operation" because the lambda uses a dynamic type.
How can I set the selected option on the DropDownList without resorting to jQuery?
I would also rather not make a template or custom helper.
Model
public class Thing : Base {
public virtual Nullable<int> OptionID { get; set; }
public virtual Option Option { get; set; }
}
public class Option : Base {
public virtual ICollection<Thing> Things { get; set; }
}
public class Base {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
Controller
public ActionResult Edit(int Id) {
return View(new ViewModel(context, new Thing()));
}
View
@model MvcApp7.Models.ViewModel
@{
var Entity = (dynamic)Model.Entity;
}
@Html.DropDownListFor(x => Entity.OptionID , (System.Web.Mvc.SelectList)Model.Options)
ViewModel
public class ViewModel {
public ViewModel(Context context, object entity) {
this.Entity = entity;
this.Options = new SelectList(context.Options, "Id", "Name");
}
public dynamic Entity { get; set; }
public SelectList Options { get; set; }
}
EDIT: Please excuse me. I forgot that I could specify the selected option in the SelectList itself. I moved the responsibility into the ViewModel and will try to deal with it from there. However, it would still be good to know how to work around this in the View itself in case it was necessary.
I did this in the ViewModelthis.Options = new SelectList(context.Options, "Id", "Name", this.Entity.OptionID);
and this in the View@Html.DropDownList("OptionID", Model.Options)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
视图
ViewModel
View
ViewModel