On a dynamic type, how can I use DropDownListFor()?

asp.net-mvc asp.net-mvc-3 drop-down-menu expression-trees html.dropdownlistfor

Question

The next error message appears in theDropDownListFor() due to the lambda's usage of a dynamic type, "A dynamic operation may not be present in an expression tree.".

Without using jQuery, how can I change the chosen option on the DropDownList?

Additionally, I'd like not to create a template or unique 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: Excuse me, please. I overlooked the fact that I could define the chosen choice inside the SelectList itself. I transferred the accountability to the ViewModel and will attempt to handle it from there. It would still be beneficial to understand how to go around this in the View itself in case it was required.

This was done in the ViewModel.
this.Options = new SelectList(context.Options, "Id", "Name", this.Entity.OptionID);
which is in the View.
@Html.DropDownList("OptionID", Model.Options)

1
0
7/30/2011 9:28:55 PM

Popular Answer

View

@model MvcApp7.Models.ViewModel

@Html.DropDownListFor(x => 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; }
}
0
7/30/2011 7:50:12 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow