ASP.Net MVC 中模型不正确的编译时错误

Mar*_*sar 5 c# asp.net asp.net-mvc razor

有没有什么方法可以使强类型视图出现编译时错误。假设我在文件夹中有一个视图/Views/Home/Index.cshtml,其中包含以下代码和强类型模型:

@model CSTemplate.Models.Home.HomeIndexModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
Run Code Online (Sandbox Code Playgroud)

然后位于的控制器/Controllers/HomeController.cs将返回以下代码。

public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            List<string> s = new List<string>();
            return View(s);
        }

    }
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,由于 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'.
Run Code Online (Sandbox Code Playgroud)

在这种模型类型不匹配的情况下,有什么方法可以得到编译时错误而不是运行时错误,或者是否有任何解决方法?

Mar*_*sar 1

从我们在这个问题中的讨论来看,似乎没有针对这种情况的建议解决方法。由于 View 将 type 的 model 作为参数object,因此如果您错误地传递了与 View 的严格类型模型不同类型的模型,编译器不会抱怨。遗憾的是,如果您需要更改视图的严格类型模型的类型,编译器不会通知您以前的不一致模型被传递给视图,但此类错误仅在运行时才会通知。