问题
Trying to create an editor template using a dropdownlist in MVC4. I can get the dropdownlistfor to work directly in the view as such:
@Html.DropDownListFor(model => model.Item.OwnerId, new SelectList(Model.DDLOptions.CustomerOptions, "Value", "DisplayText"))
But then to "generify" it and put it into an editor template, I cannot get it to work.
Here is what I am trying in my EditorTemplate partial:
@Html.DropDownListFor(model => model, new SelectList(Model.DDLOptions.CustomerOptions, "Value", "DisplayText"))
I am getting the error:
Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'int' does not contain a definition for 'DDLOptions'
Model.DDLOptions.CustomerOptions
is of type IEnumerable<DDLOptions<int>>
:
public class DDLOptions<T>
{
public T Value { get; set; }
public string DisplayText { get; set; }
}
Does this error have something to do with DDLOptions being a generic?
回答1:
This line is the problem:
@Html.DropDownListFor(model => model, new SelectList(Model.DDLOptions.CustomerOptions, "Value", "DisplayText"))
Your model is simply an int, based on the code above, but then you're calling new SelectList(Model.DDLOptions.CustomerOptions, "Value", "DisplayText")
in the partial too, referencing Model.DDLOptions, which does not exist in your model in the editor template. Your model is just an int.
There are several ways to do this, one of which is creating a custom model class for your item owner and have it contain the ownerID and the DDLOptions. Another would be to stick the DDLOptions in the ViewBag, but I usually stay away from that as I prefer using well-written, view-specific view models.
I hope this helps.
来源:https://stackoverflow.com/questions/14219335/move-html-dropdownlistfor-into-editortemplate