【问题标题】:Pass Objects from a controller to a view MVC [duplicate]将对象从控制器传递到视图 MVC [重复]
【发布时间】:2016-07-25 16:46:40
【问题描述】:

我开始了一份新工作,我们必须使用 MVC 5 创建一个应用程序,我没有 .NET 经验,所以我不确定我是否使用了最佳实践。

我有 2 个模型 ClassRom 和 Student,

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

 public class ClassRom
{
    public int ID { get; set; }
    public string Name { get; set; }
}

我正在使用 ViewBag 将 ICollection 从控制器传递到视图

IList<ClassRom> classes = db.Classes.ToList();
IList<Student> students = db.Students.ToList();
ViewBag.classes = classes;
ViewBag.students = students;
return View();

并在视图中使用数据

<div>
@foreach (var student in ViewBag.students)
{
    <div>@student.Name</div>
    <div>@student.Age</div>
}  

它可以很好地满足我的需要,无论如何,如果我添加一个脚手架控制器,它将创建如下内容:

public ActionResult Index()
    {
        return View(db.Students.ToList());
    }

还有风景

@model IEnumerable<School.Models.Student>
@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Age)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
        @Html.ActionLink("Details", "Details", new { id=item.ID }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.ID })
    </td>
</tr>

}

我的问题是,我做错了吗?我应该使用@model IEnumerable 而不是 ViewBag 吗?

【问题讨论】:

  • 有些人使用 ViewBag 传输数据,有些用户使用强类型方法(您的第二种方法)。我个人更喜欢避免 ViewData/ViewBag 并尝试使用强类型方法。一个区别是,我不使用从我的 ORM 工具创建的实体类(这将使我的视图与该类紧密耦合),而是使用视图特定的视图模型(简单的 POCO)。 Here is a good read给你更多的想法

标签: .net asp.net-mvc entity-framework viewbag


【解决方案1】:

最好使用@model IEnumerable,因为:

  • 它是静态类型的。 ViewBag 是动态的,因此您会失去类型安全性。
  • 它带来了更简洁的设计,其中组件(ViewModelsModels 可以重复使用)。

PS:我相信ClassRom 应该是ClassRoom

祝你好运!

【讨论】:

  • 使用@model 而不是ViewBag(或其他方式)如何使模型/视图模型更可重用?
  • @Luke 当使用ViewBag 将值从控制器传递到视图时,没有ModelViewModel。所以没有办法重用这些类。
  • 这对我来说毫无意义,当然你可以重用这些类。
【解决方案2】:

在正常情况下,您应该使用在您的视图中使用@model@Model 的模型。 @model(小写)用于定义模型的类型。

如果您要传递您自己的类的实例,如下所示:

public class MyClass
{
    public IEnumerable<string> MyProperty { get; set; }
}

您可以将类型定义为@model MyClass,并在您的视图中使用@Model.MyProperty 访问这些值。

通常,最佳做法是不要使用 ViewBag 将模型传递给视图,并且在您的视图中使用 @Model 将无法访问。为了使用@Model 在您的视图中访问值,您需要像这样返回传递:

public ActionResult Index()
{
    // Create your model and set the values
    var myModel = new MyClass
    {
        MyProperty = new List<string> { "First Value", "Second Value" }
    };

    // Return the model back to your view for access using @Model
    return View(myModel);
}

【讨论】:

    【解决方案3】:

    在创建视图时,我总是会使用模型。 viewbag 太松了,我不喜欢。 IEnumerable 适用于模型,因为从模型的角度来看,它是一个不可变的集合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-25
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多