使用Massive ORM填充下拉列表



我使用MVC 3和Massive ORM。

我想知道如何使用Massive ORM填充下拉列表以从数据库中获取数据。

我使用ViewData["Categoreis"]传递我的类别列表给我的视图。它将数据传递给视图,但是当我试图在浏览器中加载页面时,我得到了这个错误消息:

数据绑定:"System.Dynamic。ExpandoObject'不包含属性名称为"CategoryID"。

我的下拉列表是这样的:

@Html.DropDownListFor(model => model.CategoryID, new SelectList(ViewData["Categories"] as IEnumerable<dynamic>, "CategoryID", "Name"), "--Category--")
谁能解决我的问题?

我现在使用的是Massive。下面是我如何从数据库中的一个表中填充国家下拉列表:

这是在我的控制器:

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 });

这是DetailsModel

里面的Countries属性
public IEnumerable<SelectListItem> Countries { get; set; }

在我看来:

@Html.LabelFor(m => m.Country)
@Html.DropDownList("Country", Model.Countries)
@Html.ValidationMessageFor(m => m.Country)

对我来说很有魅力

我看起来像是有一个名为KeyValues的大规模方法用于此目的。目前它在源代码的第360行。它返回一个字典而不是一个Expando。我假设您继续在代码的其他地方使用Expando。

方法签名如下:

/// This will return a string/object dictionary for dropdowns etc  
public virtual IDictionary<string, object> KeyValues(string orderBy = "") {...}

我使用ViewData["Categoreis"]将我的类别列表传递给我的视图

我建议你使用模型,忘记ViewData/ViewBag。例如,定义以下视图模型:

public class MyViewModel
{
    public int CategoryID { get; set; }
    public SelectList Categories { get; set; }
}

并在控制器中填充模型并传递给视图:

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);
}

最后在强类型视图中:

@model MyViewModel
@Html.DropDownListFor(x => x.CategoryID, Model.Categories, "--Category--")

最新更新