2011-09-17 114 views
2

即时通讯使用MVC 3和大规模的ORM。使用Massive ORM填充下拉列表?

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

我使用ViewData [“Categoreis”]将我的类别列表传递给我的视图。它传递的数据的看法,但我得到这个errormessage的,当我尝试加载该页面在浏览器中:

数据绑定:“System.Dynamic.ExpandoObject”不包含 属性名称为“类别ID ”。

这是我的下拉列表的样子:

@Html.DropDownListFor(model => model.CategoryID, new SelectList(ViewData["Categories"] as IEnumerable<dynamic>, "CategoryID", "Name"), "--Category--") 

有谁知道我的问题的解决方案?

+0

我怀疑你是通过不包含该属性的模型'CategoryID'作为错误信息说,你可以检查你的域模型,或模型你传递的包含上述属性 – Rafay

+0

我有我的模型,即时通讯使用的CategoryID。我使用动态填充下拉列表。如果我遵循调试模式,它是如何工作的,我从数据库中获得CategoryID和Name。我只是不知道如何将CategoryID和Name链接到我的选择列表中的值和文本字段。 – Raskolnikoov

+0

也许这个链接将帮助http://stackoverflow.com/questions/4740969/how-to-databind-a-gridview-to-an-expandoobject/5145419#5145419 – Rafay

回答

3

目前我正在使用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 }); 

这里是Countries属性,它是在我的DetailsModel

public IEnumerable<SelectListItem> Countries { get; set; } 

在我看来:

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

对我来说就像一个魅力。

0

我使用计算机[“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--") 
+0

现在没有同样的错误消息。 :/ – Raskolnikoov

+0

@Raskolnikoov,你从应用程序中删除了所有的ViewBag吗?当我说我的意思是所有的和来自任何地方。 –

+0

是的,没有viewdata/viewbag。 – Raskolnikoov

1

我看起来有一个称为KeyValues的Massive方法用于此目的。目前它是line 360 in the source code。它返回一个字典而不是一个Expando。我假设你继续在你的代码中的其他地方使用你的Expando。

这里是方法的签名:

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