gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:25:17 25 4
gpt4 key购买 nike

当我想在 .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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com