namespace TaskList.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
private TaskListDataContext DB = new TaskListDataContext();
//Task tasks = new Task();
//Display a list of Tasks
public ActionResult Index()
{
var tasks = from t in DB.Tasks
orderby t.EntryDate descending
select new TaskList.Models.Task()
{
Id = t.Id,
Task1 = t.Task1,
IsCompleted = t.IsCompleted,
EntryDate = t.EntryDate
};
return View(tasks);
}
//Display a form for creating a new Task
public ActionResult Create()
{
return View();
}
//Adding a new task to the database
public ActionResult CreateNew(string tasktext)
{
//Add the new task to the database
Task newTask = new Task();
newTask.Task1 = tasktext;
newTask.IsCompleted = false;
newTask.EntryDate = DateTime.Now;
DB.Tasks.InsertOnSubmit(newTask);
DB.SubmitChanges();
return RedirectToAction("Index");
}
//Mark a task as complete
public ActionResult Complete()
{
//Database Logic
return RedirectToAction("Index");
}
}
}
查看:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<TaskList.Models.Task>>"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<div>
<h1>My Tasks</h1>
<ul>
<% foreach (TaskList.Models.Task task in ViewData.Model)
{%>
<li>
<% task.Task1.ToString(); %>
</li>
<% } %>
</ul>
<br /> <br />
<a href='<%=Url.Action("Create")%>/filename'>Add my Tasks</a>
</div>
</body>
</html>
模型使用LINQ講座
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Tasks")]
public partial class Task : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Id;
private string _Task1;
private bool _IsCompleted;
private System.DateTime _EntryDate;
}
當我試圖運行作出該應用程序顯示我的錯誤
「不允許在查詢 中顯式構造實體類型'TaskList.Models.Task'。」
在foreach循環中。
其實我試圖創建一個C#veriosn在VB中建立的應用程序在這裏。
http://www.asp.net/mvc/videos/mvc-2/how-do-i/creating-a-tasklist-application-with-aspnet-mvc
我認爲這可以幫助你http://stackoverflow.com/a/7362796/1239554 – shanish
http://stackoverflow.com/questions/787296/explicit-construction-of-entity-type-in-query-is -not-allowed – ema
非常感謝,但錯誤得到糾正,使用har07的解決方案,你可以請幫助我這個「視圖仍然沒有顯示任務名字符串按照我已經在視圖中添加的foreach循環」 – aroraarjita