问题描述
我对ASP.NET MVC很新,其实这是我第一次的项目中使用它。我想建立简单的任务列表。我在ASP.NET还算不错,但几乎一无所知ASP.NET MVC或LINQ所以请记住这一点,一边回答。
I'm quite new to ASP.NET MVC in fact this is my first ever project using it. I want to build simple TaskList. I'm fairly fine in ASP.NET but know almost nothing about ASP.NET MVC or Linq so please keep this in mind while answering.
我使用codeFirst实体Frameword产生分贝。
I'm using CodeFirst Entity Frameword to generate Db.
我有两个表用户(ID,名称)和任务(ID,用户ID,名称)。我创建了保存用户和任务特性的两个模型对象。因此,而不是有INT用户ID作为数据库的设计建议,我有任务类内的用户类任务连接到特定的用户。
I have two tables Users(id,name) and Tasks(id,userid,name). I have created two Model objects which hold Users and Tasks properties. So instead of having int userID as database design would suggest i have an User class inside of Task class to connect Task to certain User.
不知何故,我已经成功地创建使用LINQ加入
Somehow i've managed to create join using LINQ
var model = from t in _db.Tasks
join u in _db.Users on t.User.ID equals u.ID
select new { UserID = u.ID,UserName = u.Name,t.Name,t.ID };
return View(model);
但我不能将其绑定到一个视图,我把它绑定到任务模型这可能导致此错误。
but i cannot bind it to a view, i binded it to Task Model which probably cause this error.
我要如何解决这个问题,也许有某种视图模型我需要创建或类似的东西?
How do i solve this issue, maybe there is some kind of ViewModel i need to create or something like that?
谢谢...
推荐答案
您应该创建一个视图模型,并把它传递到您的视图:
You should create a ViewModel and pass it to your view:
public class TaskViewModel
{
public int TaskId { get; set; }
public string TaskName { get; set; }
public int UserId { get; set; }
public int Username { get; set; }
}
不是创建一个强类型的视图:
Than create a strongly typed view:
@model IEnumerable<YourNamespace.Models.TaskViewModel>
//Display model data
和LINQ查询:
And Linq query:
var model = from t in _db.Tasks
join u in _db.Users on t.User.ID equals u.ID
select new TaskViewModel
{
TaskId = t.ID,
TaskName = t.Name,
UserId = u.ID,
Username = u.Name
};
这篇关于如何使在ASP.NET MVC3此模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!