路由问题MVC

本文关键字:MVC 问题 路由 | 更新日期: 2023-09-27 18:22:42

我正在学习MVC,目前正在研究路由。

我有以下问题:这是我的RegisterRoutes方法:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute("Customer", "{controller}/{action}/{objCustomer}",
            new {controller = "Customer", action = "CreateCustomer", id = UrlParameter.Optional});
}

如果我运行我的应用程序,应该hxxp://localhost:12454/在CustomerController中不显示CreateCustomer操作调用的视图,换句话说,URL应该是这样的吗hxxp://localhost:12454/Customer/CreateCustomer

注意:我用hxxp替换了http,以避免尝试创建链接

我在这里有什么理解不正确的地方?

这是我的全部Global.asax.cs课程。

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute("Customer", "{controller}/{action}",
              new { controller = "Customer", action = "CreateCustomer", UrlParameter.Optional});
    }
}

这是我的客户总监:

public class CustomerController : Controller
{
    // GET: Customer
    public ActionResult ShowCustomer(Customer objCustomer)
    {
        return View(objCustomer);
    }
    public ActionResult CreateCustomer()
    {
        return View();
    }
}

路由问题MVC

您在路由中使用的不是'id',而是objCustomer,然后您必须将objCustomer指定为可选路由参数。

修改路线,如下所示:

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  routes.MapRoute("Customer", "{controller}/{action}/{objCustomer}",
        new {controller = "Customer", action = "CreateCustomer", objCustomer = UrlParameter.Optional});
}

在AppStart文件夹中的routeconfig.cs文件中创建所有自定义路由,不要忘记将此自定义路由放在默认路由之上