asp.net - .net MVC Controller 究竟如何知道要返回哪个 View()?

标签 asp.net .net asp.net-mvc controller

当我想在 .net 中调用一个新页面时,比如“About.cshtml”页面,我在 HomeController 中使用以下代码:

public ActionResult About()
{
    ViewBag.Title = "About";
    return View();
}

要调用它,我会使用指向“/Home/About”的链接。例如,如果我想创建一个名为“Contact.cshtml”的新页面,我会复制上面的内容并将 About 替换为 Contact。

我知道“/Home”中的路由调用了HomeController。但是,该 Controller 究竟如何知道返回 About.cshtml 页面?我假设它是基于函数的名称。但这对我来说听起来不对。 About() 不是像 Get() 或 Post() 这样的 HTTP 动词,并且函数的名称通常不应定义它的作用,除非它已经存在。

另外,View() 到底是什么时候定义的,什么时候分配给 About.cshtml 页面的?

最后,是否有一个属性允许我返回具有不同函数名称的 About.cshtml 页面(因为我可以设置一个函数来响应具有 [HttpGet] 属性的 Get)?

最佳答案

But how, exactly, does that controller know to return the About.cshtml page?

因为操作方法名称是About:

public ActionResult About()

路由通过 URL 找到了那个方法:

/Home/About

如果 URL 不包含操作:

/Home

然后它会寻找默认操作。通常这是 Index(),由默认路由映射配置:

routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = "" }
        );

注意如果 URL 上没有提供默认值,则如何为 controlleraction 定义默认值。

the name of the function normally shouldn't define what it does

为什么不呢?函数名称​​应该完全定义该函数的作用。


Also, when exactly is View() defined

它在 the base controller class 中.


Finally, is there an attribute that would allow me to return the About.cshtml page with a different function name

本身不是属性,但您可以在调用 View() 时指定 View 名称:

return View("SomeOtherView");

关于asp.net - .net MVC Controller 究竟如何知道要返回哪个 View()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35901957/

相关文章:

javascript - 想要在 Javascript 中触发 Dropdown SelectedIndexChanged 事件

c# - 可观察到的 : ANDing sources and completion

c# - Task.WhenAny 和未观察到的异常

javascript - 如何创建C#删除确认框

c# - 使用 NavigateUrl 和 Eval() 的超链接。错误在哪里?

Page_Load 中的 C# 将代码放在 <html> 之上

asp.net - 在web.config中指定子目录页面的母版页

c# - 从电子邮件字符串获取主机.net core

javascript - 使用 ajax 返回 Controller 方法值

javascript - 如何永久显示style="display:none"div元素?