MVC 路由 及 遇到问题记录

来源:互联网 发布:淘宝网店管理技巧 编辑:程序博客网 时间:2024/05/28 04:53

  1. MVC 路由
  2. 重定向
  3. 问题记录
1)MVC 路由
入口方法:
(Global.asax)Application_Start()--->(App_Start/RouteConfig.cs)RegisterRoutes()--->(Controllers/)Controller--->(Views/)Action--->(Views/Action/)View
其中Application_Start()代码如下:

<span style="font-size:14px;font-weight: normal;"><span style="font-size:14px;">namespace MvcAspxMovie{    public class RouteConfig    {        public static void RegisterRoutes(RouteCollection routes)        {            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");            routes.MapRoute(                name: "Default",//路由名称                url: "{controller}/{action}/{id}",//带有参数的URL                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }//默认参数            );        }    }}</span></span>

2)重定向:页面跳转传参(RedirectToAction())

在MVC中页面后台中常用的页面跳转方法有几种,如:return View()、return RedirectToAction().
  一般情况下我们返回的都是本页面,所以使用return View()就够了.有时候我们也会遇到返回的页面不是本页面的,就要用到return RedirectToAction();方法了。
举例如下,通过RedirectToAction调用跳转到HelloWorld(),页面返回“helloworld”。
        public string HelloWorld()        {            return "hello world";        }        public ActionResult TestRedirect()        {            return RedirectToAction("HelloWorld");        }
遇到需要传参的情况,则需要对RedirectToAciton()扩展
RedirectToAction(string ActionName);  //<span style="font-family: Arial; font-size: 14px; line-height: 26px;">跳转到同一Controller 里面的不同Action</span>RedirectToAction(string ActionName, object viewData);  //<span style="font-family: Arial; font-size: 14px; line-height: 26px;">跳转到同一Controller 里面的不同Action,含参数</span>RedirectToAction(string ActionName, string ControllerName);  //<span style="font-family: Arial; font-size: 14px; line-height: 26px;">跳转到不同Controller 里面的不同Action</span>RedirectToAction(string ActionName, string ControllerName, object viewData); //<span style="font-family: Arial; font-size: 14px; line-height: 26px;">跳转到不同Controller 里面的不同Action,含参数</span>
<span style="font-family: Arial; font-size: 14px; line-height: 26px;"><span style="font-family: Arial; font-size: 14px; line-height: 26px;">如:RedirectToAction("Index","Home",new {msg="操作成功",name="admin"});</span></span>
<%: Html.ActionLink("Edit", "Edit", new { id=item.ID }) %> 
举例如下,调用TestRedirect()最终页面返回“hello bailang”
        public string HelloWorld(string str)        {           return "hello "+str;        }        public ActionResult TestRedirect()        {            return RedirectToAction("HelloWorld",new{str="bailang"});        }




3)问题记录
20160104 初学MVC 遇到新建一个controller,默认action 是index,URL输入 http://localhost:15683/TestThumbnail 默认为http://localhost:15683/TestThumbnail/index,但未知修改会造成再次URL输入默认到index不起作用,必须定位输入http://localhost:15683/TestThumbnail/index,原因发现为:在根目录下生成同名controller的目录。
解决方法:删除该目录即可。


0 0