0

我刚开始学习和探索 ASP.NET MVC 4.5,我试图弄清楚HtmlHelper. 显然,当我在浏览器上运行应用程序时,我看到 <%= ViewData["greeting"] %> , world (from the view)!但没有看到 helper 的值ViewData。要么我做错了,要么 Visual Studio 不支持HtmlHelpers ,或者您可能必须更改设置才能使其正常工作。我尝试下载更新,但也没有用。我还尝试在 .NET 框架 3.5、4 和 4.5 下创建新项目,但它似乎根本不起作用。

这里是一部分index.cshtml

@{
    ViewBag.Title = "Home";
}
        
<body>
  <h2>Home</h2>
  <%= ViewData["greeting"] %> , world (from the view)!
</body>

homeController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
        
namespace PartyInvites_2.Controllers
{
    public class homeController : Controller
    {
        //
        // GET: /home/
        
        public ViewResult Index()
        {
            int hour = DateTime.Now.Hour;
            ViewData["greeting"] = (hour < 12 ? "good morning" : "good evening");
        
            return View();
        }
    }
}
4

1 回答 1

0

(这个答案取自@codingbiz 的评论;我没有写这个解决方案,但 OP 发现它很有帮助)

您使用的是 razor 还是 asp.net 模板?剃刀语法应该是@ViewData["greeting"]

根据 OP,修复语法是有效的。我相信这就是它的样子:

@{
    ViewBag.Title = "Home";
}
        
<body>
  <h2>Home</h2>
  @ViewData["greeting"] , world (from the view)!
</body>
于 2021-12-09T01:29:23.923 回答