ASP.NET MVC Viewmodel不返回任何内容 [英] ASP.NET MVC Viewmodel returns nothing

查看:53
本文介绍了ASP.NET MVC Viewmodel不返回任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图创建一个简单的应用程序,但是在尝试使用viewmodel时,我的视图没有返回任何内容.我认为"db.[TableName] .ToList();"仅适用于域模型,还不够,并且在使用视图模型时选择应该以不同的方式进行,但我不知道该怎么做它.请帮忙.谢谢.

Trying to make a simple application but my view returns nothing when trying to use a viewmodel. I assume the "db.[TableName].ToList();", which works when applied on a domain model, is not enough and the selection should happen in a different way when using a viewmodel, but I have no idea how to do it. Please help. Thank you.

Town.cs

using System.Collections.Generic;

namespace City.Models
{
    public class Town
    {
        public Town()
        {
            Streets = new List<Street>();
        }
        public int TownId { get; set; }
        public string TownName { get; set; }
        public virtual ICollection<Street> Streets { get; set; }
    }
}

Street.cs

using System.Collections.Generic;

namespace City.Models
{
    public class Street
    {
        public Street()
        {
            Houses = new List<House>();
        }
        public int StreetId { get; set; }
        public string StreetName { get; set; }
        public virtual ICollection<House> Houses { get; set; }
    }
}

House.cs

namespace City.Models
{
    public class House
    {
        public int HouseId { get; set; }
        public string HoueseName { get; set; }
        public int StreetId { get; set; }
        public virtual Street Street { get; set; }
    }
}

Floor.cs

namespace City.Models
{
    public class Floor
    {
        public int FloorId { get; set; }
        public int FloorNumber { get; set; }
        public int FireExtinguisherId { get; set; }
    }
}

FireExtinguisher.cs

namespace City.Models
{
    public class FireExtinguisher
    {
        public int FireExtinguisherId { get; set; }
        public string FireExtinguisherName { get; set; }
        public int FloorId { get; set; }
    }
}

MyViewModel.cs

namespace City.Models
{
    public class MyViewModel
    {
        public MyViewModel()
        {
            Town = new Town();
            Street = new Street();
            House = new House();
            Floor = new Floor();
            FireExtinguisher = new FireExtinguisher();
        }

        public int MyViewModelId { get; set; }
        public Town Town { get; set; }
        public Street Street { get; set; }
        public House House { get; set; }
        public Floor Floor { get; set; }
        public FireExtinguisher FireExtinguisher { get; set; }
    }
}

ApplicationDbContext.cs

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public DbSet<Town> Towns { get; set; }
        public DbSet<Street> Streets { get; set; }
        public DbSet<House> Houses { get; set; }
        public DbSet<Floor> Floors { get; set; }
        public DbSet<FireExtinguisher> FireExtinguishers { get; set; }
        public DbSet<MyViewModel> MyViewModels { get; set; }
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

HomeController.cs (我认为问题出在这里)

HomeController.cs (I think the problem lies here)

using System.Linq;
using System.Web.Mvc;
using City.Models;

namespace City.Controllers
{
    public class HomeController : Controller
    {
        private ApplicationDbContext db;
        public HomeController()
        {
            db = new ApplicationDbContext();
        }
        public ActionResult Index()
        {
            return View(db.MyViewModels.ToList());
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

Index.cshtml

@model IEnumerable<City.Models.MyViewModel>

<h2>Map information</h2>

<div class="container">
    <table class="table">
        <thead>
            <tr>
                <th>Town</th>
                <th>Street</th>
                <th>House</th>
                <th>Floor</th>
                <th>FireExtinguisher</th>
            </tr>
        </thead>
        @foreach (var item in Model)
        {
            <tbody>
                <tr>
                    <td>@(item.Town.TownName)</td>
                    <td>@(item.Street.StreetName)</td>
                    <td>@(item.House.HoueseName)</td>
                    <td>@(item.Floor.FloorNumber)</td>
                    <td>@(item.FireExtinguisher.FireExtinguisherName)</td>
                </tr>
            </tbody>
        }
    </table>
</div>

即使我在数据库中有测试数据,这也是我运行它时看到的一切:

Even though I have test data in the db, this is all what I see when I run it:

图片在这里

请告诉我我应该解决什么,如何获取数据.谢谢

Please tell me what should I fix, how to get data retrieved. Thanks

编辑@CrowdCoder

此处有新图片

推荐答案

我认为您对视图模型的理解不正确.

I think your understanding about view model is incorrect.

视图模型是用于在视图和操作方法之间传输数据的类.视图模型特定于视图.因此,如果视图仅需要显示2个属性( Name Age ),则视图模型将仅具有这2个属性.无需将实体模型中的所有属性带到视图模型类.

View model is a class to transfer data between your view and your action method. View model is specific to the view. So if your view needs to display only 2 properties (Name and Age), your view model will have only those 2 properties. No need to bring all the properties from your entity model to the view model class.

我看到您在数据库上下文中添加了一个新集合,

I see that you added a new collection to the your db context,

public DbSet<MyViewModel> MyViewModels { get; set; }

这没有任何意义.正如我之前提到的,视图模型是UI关注的问题.它不应在您的数据访问代码中.另外,请勿在视图模型中混合由ORM层创建的实体.

This does not makes any sense. As i mentioned earlier, view models are UI concerns. It should not be in your data access code. Also do not mix the entities created by your ORM layer in your view model.

视图模型也是简单的POCO.它应该是具有属性的精简类.加载属性值是您的责任.您可以在操作方法或从操作方法调用的其他方法中执行此操作.

Also view models are simple POCOs. It should be lean-flat classes with properties. It is your responsibility to load the property values. You can do that in your action method or another method called from your action method.

假设您要显示带有街道名称的房屋列表,您将创建一个这样的视图模型

Let's say you want to display a list of houses with it's street name, you will create a view model like this

public class HouseViewModel
{
   public int HouseId { set; get;}
   public string HoueseName { set;get;}
   public string StreetName { set;get; }
}

现在,在您的视图中,您只需访问这些属性

Now in your view, you simply access these properties

@model IEnumerable<HouseViewModel>
<table>
@foreach(var item in Model)
{
    <tr>
         <td>@item.HouseId </td>
         <td>@item.HoueseName </td>
         <td>@item.StreetName </td>
    </tr>
}
</table>

为使此代码正常工作,您需要确保要创建 HouseViewModel 的列表,并将其从操作方法发送到视图.

Ofcourse, for this code to work, you need to make sure you will be creating a list of HouseViewModel and send it to the view from your action method.

public ActionResult Index()
{
   var list= new List<HouseViewModel>{
               new HouseViewModel { HouseId =1,HoueseName ="Abc", StreetName ="Detroit"},
               new HouseViewModel { HouseId =2,HoueseName ="Xyz", StreetName ="Novi"}
   };
   return View(list);
}

现在您可以看到我们如何使用视图模型将数据从操作方法传输到视图.在这里,我们只是对要发送的列表中的项目的属性值进行了硬编码.我们可以根据需要更新它以从您的EF数据库上下文中读取.

Now you can see that how we are using view model to transfer data from the action method to the view. Here we just hard coded the property values for the items in the list we are sending. We can update that to read from your EF db context as needed.

让我们阅读所有房屋,使用LINQ投影为该集合中的每个项目创建一个 HouseViewModel 对象,并分配属性值.

Let's read all the Houses, use LINQ projection to create a HouseViewModel object for each item in that collection and assign the property values.

public ActionResult Index()
{
   var houses = db.Houses
                  .Select(a=>new HouseViewModel 
                                  { HouseId =a.HouseId,
                                    HoueseName =a.HouseName,
                                    StreetName = a.Street.StreetName
                                  })
                  .ToList();
   return View(houses);
}

这篇关于ASP.NET MVC Viewmodel不返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆