对于强类型视图,是否有任何可能存在编译时错误的方法。假设我在文件夹/Views/Home/Index.cshtml
中有一个视图,其中包含以下代码&强类型模型:
@model CSTemplate.Models.Home.HomeIndexModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
然后位于/Controllers/HomeController.cs
的控制器将返回以下代码。
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
List<string> s = new List<string>();
return View(s);
}
}
正如您所看到的,由于View()接受一个对象作为模型,编译器不会抱怨模型无效并且会输出运行时错误,即:
Server Error in '/' Application.
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.String]', but this dictionary requires a model item of type 'CSTemplate.Models.Home.HomeIndexModel'.
在这种模型类型不匹配的情况下,有没有办法可以获得编译时错误而不是运行时错误,或者有没有解决方法?
答案 0 :(得分:1)
根据我们在这个问题中的讨论,似乎没有针对这种情况的建议解决方法。由于View将类型object
的模型作为参数,因此如果您错误地传递了与View的严格类型模型不同类型的模型,则编译器不会抱怨。遗憾的是,如果您需要更改View的严格类型模型的类型,编译器将不会通知您之前传递给视图的此类不一致模型,但此类错误仅在运行时通知。
答案 1 :(得分:0)
我上传了一个nuget包来解决这个问题,它会生成真正强烈命名的视图。
检查一下
答案 2 :(得分:-1)
return View(s);
应该返回
CSTemplate.Models.Home.HomeIndexModel //this is the type model expecting
不
List<string> //this is the type you are returning to the model