Populate dropdownlist using Massive ORM?
Im using MVC 3 and Massive ORM.
I won开发者_Python百科dering how I could populate a dropdownlist using Massive ORM to get my data from the database.
I pass my list of categories to my view using ViewData["Categoreis"]. It passed the data to the view, but I get this errormessage when I try to load the page in my browser:
DataBinding: 'System.Dynamic.ExpandoObject' does not contain a property with the name 'CategoryID'.
This is how my dropdownlist looks like:
@Html.DropDownListFor(model => model.CategoryID, new SelectList(ViewData["Categories"] as IEnumerable<dynamic>, "CategoryID", "Name"), "--Category--")
Does anybody have a solution for my problem?
I'm using Massive at the moment. Here's how I've populated a countries dropdown from a table in the database:
This is in my controller:
DetailsModel model = new DetailsModel();
var _countries = new Countries(); //Massive class
model.Countries = _countries.All().Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.Name });
Here is the Countries
property that is inside my DetailsModel
public IEnumerable<SelectListItem> Countries { get; set; }
In my view:
@Html.LabelFor(m => m.Country)
@Html.DropDownList("Country", Model.Countries)
@Html.ValidationMessageFor(m => m.Country)
Works like a charm for me.
I it looks like there is a Massive method called KeyValues for this purpose. Currently it is line 360 in the source code. It returns a dictionary rather than an Expando. I assume you continue to use your Expando elsewhere in your code.
Here is the method signature:
/// This will return a string/object dictionary for dropdowns etc
public virtual IDictionary<string, object> KeyValues(string orderBy = "") {...}
I pass my list of categories to my view using ViewData["Categoreis"]
I would recommend you to use models and forget about ViewData/ViewBag. For example define the following view model:
public class MyViewModel
{
public int CategoryID { get; set; }
public SelectList Categories { get; set; }
}
and in the controller populate the model and pass to the view:
public ActionResult Index()
{
var categories = _repository.GetCategories();
var model = new MyViewModel
{
// this assumes that categories is an IEnumerable<T>
// where T is some domain model having CategoryID and Name properties
Categories = new SelectList(categories, "CategoryID", "Name")
};
return View(model);
}
and finally in your strongly typed view:
@model MyViewModel
@Html.DropDownListFor(x => x.CategoryID, Model.Categories, "--Category--")
精彩评论