3

有什么方法可以让强类型视图出现编译时错误。假设我在文件夹中有一个视图,其中/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'.

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

4

3 回答 3

1

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

于 2012-12-05T12:57:39.847 回答
0

我已经上传了一个 nuget 包来解决这个问题,它会生成真正强命名的视图。
在这里检查

https://www.nuget.org/packages/StronglyTypedViews/

于 2013-07-20T22:44:05.870 回答
-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
于 2012-12-04T12:42:27.113 回答