使用MVC 6 EF将数据传递到视图

use*_*176 1 c# model-view-controller asp.net-mvc entity-framework viewbag

由于我看到有几个人建议不要使用ViewBag,我想知道如何正确使用:

返回视图()

我已经读过您需要使用所谓的ViewModel,但是当您使用Entity Framework时,这些似乎不适用.

如何将数据传递给View?如何在View中访问所述数据?

jan*_*ann 6

您可以传递"视图模型"或对象,如:

public ActionResult Index() {
    var model = new MyViewModel();
    model.MyProperty = "My Property Value"; // Or fill the model out from your data store. E.g. by creating an object to return your view model: new CreateMyViewModel();

    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

在您的视图页面(此处为Index.cshtml)中,将其添加到顶部:

@model MyViewModel
Run Code Online (Sandbox Code Playgroud)

并访问MyViewModel上的属性,如:

@Model.MyProperty
@Html.DisplayFor(model => model.MyProperty)
Run Code Online (Sandbox Code Playgroud)

有关更深入的答案,请查看:MVC中的ViewModel是什么?