Razor 助手 - 奇怪的 InvalidOperationException
Razor helpers - strange InvalidOperationException
在我的 ASP.NET 的 App_Code 文件夹中有一个包含 Razor 助手的 Common.cshmtl 文件] MVC 5 项目。
页面视图(让它被称为 Production.cshtml)使用了很多来自 Common.cshmtl 的助手,例如:
@Common.Helper1();
...
@Common.Helper2();
...
@Common.Helper3();
的建议
由于应用程序代码中的错误,我可以看到在页面上单击按钮后执行了 2 个几乎相等的 AJAX 请求。
我收到一个错误
An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code.
一个错误还声称代码正在尝试修改 foreach 运算符中的集合。这里看起来像是应用程序代码的正常错误。
但是在调试代码以发现某个错误时,我可以看到它在 Product.cshtml 的某个非常随机的地方中断,没有连接到 foreach。上层文件和底层文件都找不到foreach。此外,当再次尝试调试时(当然没有修改)——我可以看到这次中断发生在另一个文件中——在 Common.cshtml 中!
一次又一次地重复证明了这种奇怪的行为。
可能是什么原因?
问题是由于您使用了错误的 MVC 5 指南。ASP.NET 网页项目使用不同的结构,您不需要将 HTML 助手在 App_Code
文件夹中,它们应该在 .cs
文件中,而不是 .cshtml
文件中。
有关构建 MVC HTML 助手的帮助,请参阅以下教程。
http://www.codeproject.com/Articles/787320/An-Absolute-Beginners-Tutorial-on-HTML-Helpers-and
http://www.dotnet-tricks.com/Tutorial/mvc/N50P050314-Understanding-HTML-Helpers-in-ASP.NET-MVC.html
http://www.c-sharpcorner.com/UploadFile/d98ae4/creating-custom-html-helpers-in-mvc5/
在我的 ASP.NET 的 App_Code 文件夹中有一个包含 Razor 助手的 Common.cshmtl 文件] MVC 5 项目。
页面视图(让它被称为 Production.cshtml)使用了很多来自 Common.cshmtl 的助手,例如:
@Common.Helper1();
...
@Common.Helper2();
...
@Common.Helper3();
的建议
由于应用程序代码中的错误,我可以看到在页面上单击按钮后执行了 2 个几乎相等的 AJAX 请求。
我收到一个错误
An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code.
一个错误还声称代码正在尝试修改 foreach 运算符中的集合。这里看起来像是应用程序代码的正常错误。
但是在调试代码以发现某个错误时,我可以看到它在 Product.cshtml 的某个非常随机的地方中断,没有连接到 foreach。上层文件和底层文件都找不到foreach。此外,当再次尝试调试时(当然没有修改)——我可以看到这次中断发生在另一个文件中——在 Common.cshtml 中! 一次又一次地重复证明了这种奇怪的行为。
可能是什么原因?
问题是由于您使用了错误的 MVC 5 指南。ASP.NET 网页项目使用不同的结构,您不需要将 HTML 助手在 App_Code
文件夹中,它们应该在 .cs
文件中,而不是 .cshtml
文件中。
有关构建 MVC HTML 助手的帮助,请参阅以下教程。
http://www.codeproject.com/Articles/787320/An-Absolute-Beginners-Tutorial-on-HTML-Helpers-and
http://www.dotnet-tricks.com/Tutorial/mvc/N50P050314-Understanding-HTML-Helpers-in-ASP.NET-MVC.html
http://www.c-sharpcorner.com/UploadFile/d98ae4/creating-custom-html-helpers-in-mvc5/