自定义路由问题

时间:2016-08-19 18:19:35

标签: c# asp.net-mvc-4 routes

我必须制定自定义路线,但我遇到了问题。 那是我的路线

routes.MapRoute(
            name: "IndexByUserName",
            url: "{controller}/{action}/{username}",
            defaults: new { controller = "Profile", action = "Edit", username = UrlParameter.Optional }
        );

当我转到网址.../Profile/Edit/UserTest时,我收到404 Not Found错误,因为我的参数usernamenull。我的行动看起来像这样

    [Authorize]
    [HttpGet]
    public ActionResult Edit(string username)
    {

        ApplicationUser profile = db.Users.Find(username);
        if (profile == null)
        {
            return HttpNotFound();
        }
        return View(profile);
    }

    [Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id, Nickname, FirstName, LastName, SecondName, City, Address, Description, Skype, TelephoneNum")] ApplicationUser profile)
    {
        if (ModelState.IsValid)
        {
            var user = db.Users.Find(profile.Id);
            if (user == null)
            {
                return HttpNotFound();
            }
            user.UserName = User.Identity.GetUserName();
            user.FirstName = profile.FirstName;
            user.SecondName = profile.SecondName;
            user.LastName = profile.LastName;
            user.SocialNetworks = profile.SocialNetworks;
            user.Address = profile.Address;
            user.City = profile.City;
            user.TelephoneNum = profile.TelephoneNum;
            user.Description = profile.Description;
            db.Entry(user).State = EntityState.Modified;
            db.SaveChanges();
            return Redirect("/Profile/Index/" + User.Identity.Name);
        }
        return View(profile);
    }

我不知道问题所在。

2 个答案:

答案 0 :(得分:1)

您是否删除了默认路线?您的路线看起来将具有相同的默认特性,因此如果首先出现默认路线,您的应用程序将只使用该路线。

请参阅this answer了解如何解决此问题(如果这是您的问题)。

答案 1 :(得分:0)

在项目的App_Start文件夹中的RouteConfig.cs文件的RegisterRoute方法中,默认路由规则是:默认路由规则是:-ControllerName / ActionName / id

其中id是可选的。 对于前 -

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
    "Default",                                           // Route name 
    "{controller}/{action}/{id}",                 // URL with parameters 
    new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);

}

所以你想让它自定义make userName =" "在您的路由规则中。

并在您的ViewPage按钮单击事件中使用可以jquery

$("#Selector").click(function(response){
$.get("@Url.Action("ControllerName","ActionName)",{userName:"Name of User"})

});

其中selector表示编辑按钮标记的ID。

相关问题