我创建了一个名为loginController的控制器.cs并创建了一个名为login的视图.aspx
如何从登录控制器.cs调用该视图?
ActionResult
始终设置为索引,为了整洁起见,我想指定控制器在调用时使用的视图,而不是总是调用其默认索引?
希望这是有道理的。
您可以自定义 MVC 路由中的几乎所有内容 - 对路由的外观没有特别的限制(只有排序很重要),您可以以不同于方法名称的方式命名操作(通过 ActionName 属性),您可以随意命名视图(即通过按名称返回特定视图)。
return View("login");
为了实际回答问题.. 您可以在默认路由上方添加一个路由 Global.asax
:
routes.MapRoute(
"SpecialLoginRoute",
"login/",
new { controller = "Login", action = "Login", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
..虽然,如果没有正确考虑你想要实现的目标(即..改变MVC默认的功能),你最终肯定会有很多很多混乱的路线。
通过操作方法从控制器返回视图。
public class LoginController:Controller
{
public ActionResult Index()
{
return View();
//this method will return `~/Views/Login/Index.csthml/aspx` file
}
public ActionResult RecoverPassword()
{
return View();
//this method will return `~/Views/Login/RecoverPassword.csthml/aspx` file
}
}
如果需要返回其他视图(操作方法名称除外),可以显式提及它
public ActionResult FakeLogin()
{
return View("Login");
//this method will return `~/Views/Login/Login.csthml/aspx` file
}
如果要返回存在于另一个控制器文件夹中的视图,在 ~/views 中,可以使用完整路径
public ActionResult FakeLogin2()
{
return View("~/Views/Account/Signin");
//this method will return `~/Views/Account/Signin.csthml/aspx` file
}