jim*_*web 2 .net asp.net asp.net-mvc controller
当我想调用 .net 中的新页面(例如“About.cshtml”页面)时,我在 HomeController 中使用以下代码:
public ActionResult About()
{
ViewBag.Title = "About";
return View();
}
Run Code Online (Sandbox Code Playgroud)
为了调用它,我将使用“/Home/About”的链接。例如,如果我想创建一个名为“Contact.cshtml”的新页面,我会复制上面的内容并将“关于”替换为“联系人”。
我知道“/Home”中的路由调用了HomeController。但是,该控制器到底如何知道返回 About.cshtml 页面呢?我认为它是基于函数的名称。但这对我来说听起来不对。About() 不像 Get() 或 Post() 那样是 HTTP 动词,并且函数的名称通常不应该定义它的功能,除非它已经存在。
另外,View() 到底是什么时候定义的,什么时候分配给 About.cshtml 页面?
最后,是否有一个属性允许我返回具有不同函数名称的 About.cshtml 页面(因为我可以设置一个函数以使用 [HttpGet] 属性响应 Get)?
但是,该控制器到底如何知道返回 About.cshtml 页面呢?
因为操作方法名称是About
:
public ActionResult About()
Run Code Online (Sandbox Code Playgroud)
路由通过 URL 找到了该方法:
/Home/About
Run Code Online (Sandbox Code Playgroud)
如果 URL 不包含操作:
/Home
Run Code Online (Sandbox Code Playgroud)
然后它会寻找默认操作。通常这是Index()
由默认路由映射配置的:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
Run Code Online (Sandbox Code Playgroud)
请注意如何为两者定义默认值controller
以及action
URL 上是否未提供默认值。
函数的名称通常不应该定义它的作用
为什么地球上不呢?函数名称应该准确定义该函数的功能。
另外,View() 到底是什么时候定义的
它位于基本控制器类中。
最后,是否有一个属性允许我返回具有不同函数名称的 About.cshtml 页面
本身不是属性,但您可以在调用时指定视图名称View()
:
return View("SomeOtherView");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5195 次 |
最近记录: |