简体   繁体   English

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

[英]Passing data to a view with MVC 6 EF

Since I've seen several people advising against using the ViewBag I was wondering how to do it correctly using: 由于我已经看到一些人建议不要使用ViewBag,所以我想知道如何使用以下方法正确执行操作:

return View() 返回View()

I've read that you need to use so called ViewModels but those don't seem to apply when you are working with the Entity Framework. 我读过您需要使用所谓的ViewModels,但是当您使用Entity Framework时,这些似乎并不适用。

How do I pass data to the View? 如何将数据传递到视图? How do I access said data within the View? 如何在视图中访问上述数据?

You can pass a "view model" or object like: 您可以传递“视图模型”或类似的对象:

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

In your view page (here Index.cshtml) add this in the top: 在您的视图页面(此处为Index.cshtml)中,将其添加到顶部:

@model MyViewModel

And access the properties on MyViewModel like: 并访问MyViewModel上的属性,例如:

@Model.MyProperty
@Html.DisplayFor(model => model.MyProperty)

For a more in-depth answer, take a look at: What is ViewModel in MVC? 要获得更深入的答案,请看一下: MVC中的ViewModel是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM