首先,我是MVC的初学者。
我有一个名为 FinanceController
的 Controller 。我有两个名为 StoreEvaluationForm
和此控件的 SendStoreEvaluationToPdf
的 View 。我想从第二个 View 调用第一个 View 的 public static
函数,该函数在 @functions
中定义。
我猜 View 在 mvc 中有隐藏类。因为我意识到当我将鼠标悬停在第一个 View 的函数上时,VS 显示了名为 _Page_Views_Finance_StoreEvaluationForm_cshtml
的类及其名为 ASP 的命名空间。但是我找不到任何方法来访问另一个 View 的功能。在第二个 View 中,ASP 命名空间只有其名为 _Page_Views_Finance_SendStoreEvaluationToPdf_cshtml
的类。
要清楚, View 中的函数是 C# 函数而不是 javascript 函数。它的定义是:
@functions
{
public static string NumberFormatter(double? number, bool percent = false)
{
return number == null ? null : string.Format("{0}{1}", number.Value.ToString("N2"), percent ? "%" : null);
}
}
最佳答案
是的,这是可以实现的。我在 Visual Studio 2015 中使用默认 MVC 项目进行了尝试。
关于
View 的内容:
@{
ViewBag.Title = "About";
}
@functions
{
public static string DoStuff()
{
return "Content from About view.";
}
}
Index
View 的内容:
@{
ViewBag.Title = "Home Page";
}
@_Page_Views_Home_About_cshtml.DoStuff()
... (other stuff)
在 Index
View 中,_Page_Views_Home_About_cshtml
下方有一条红色波浪线显示:
The name _Page_Views_Home_About_cshtml does not exist in the current context
尽管有错误消息,但应用程序构建成功,当导航到 /Home/Index
时,我可以从 About
View 中看到消息。
关于c# - 从另一个 View 访问 View 的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38697552/