我一直在尝试使用 ASP.NET MVC 并关注 this创建基本任务列表应用程序的教程。我已经让它运行良好,一切正常,尽管视频是在 VB 中,我在将它“转换”为 C# 时遇到了一些麻烦,但由于代码示例而糊里糊涂。
现在,为了加深我的知识,我决定对系统做一个小的修改。我想更改索引页面,以便在所有任务都已完成时以红色显示“我的任务”,在有任何未完成任务时以绿色显示“我的任务”。
我在 HomeController.cs 中添加了以下函数:
public bool Uncomplete()
{
bool AnyLeft = false;
var tasks = from t in db.Tasks orderby t.EntryDate descending select t;
foreach (Task match in tasks)
{
if (match.IsCompleted == false)
{
AnyLeft = true;
}
}
return AnyLeft;
}
然后我将 Index() ActionResult 修改为如下所示:
public ActionResult Index()
{
bool AnyLeft = Uncomplete();
var tasks = from t in db.Tasks orderby t.EntryDate descending select t;
return View(tasks.ToList());
}
我最终打算在 Index.aspx 中使用以下代码:
<% if (AnyLeft == false)
{ %>
<h1 class="green">My Tasks</h1>
<% }
else
{ %>
<h1 class="red">My Tasks</h1>
<% } %>
但是,我不知道如何让 Index.aspx“意识到”AnyLeft 的值为 true 或 false。我试过了
return View(tasks.ToList(), AnyLeft);
但这会引发我无法完全破译的错误。我有一种感觉,我正在以“错误的方式”处理事情,但我想不通。
最佳答案
在 Controller 中使用它:
public ActionResult Index()
{
ViewData["AnyLeft"] = Uncomplete();
var tasks = from t in db.Tasks orderby t.EntryDate descending select t;
return View(tasks.ToList());
}
在 View 中:
<% if (!(bool)ViewData["AnyLeft"])
{ %>
<h1 class="green">My Tasks</h1>
<% }
else
{ %>
<h1 class="red">My Tasks</h1>
<% } %>
关于asp.net-mvc - 将参数传递给 ASP.NET MVC 中的 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/466752/