如何在 ASP.NET MVC 中更改默认值 url?

How to change default url in ASP.NET MVC?

我有一个 table 显示数据库中的值,我有 3 个 @Html.ActionLink 像这样

                        @Html.RouteLink("Edit", "StudentGet", new { id = item.StudentId }) |
            @Html.ActionLink("Details", "Details", new { id=item.StudentId }) |
            @Html.ActionLink("Delete", "Delete",  new { id=item.StudentId })

这些是在我创建实体控制器时自动构建的。当我单击这些链接时,我会进入新的 URL:Students(我的控制器名称)/Edit/1。(例如)。

如何将我的 URL 更改为其他内容,例如:stu-info/edit-info/ id=1

此外,这里是我的RouterConfig.cs:

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

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
            routes.MapMvcAttributeRoutes();
        } 
    }

并在 StudentsController

中执行 Edit 操作
[Route("~/stu-info/get-info/{id?}", Name = "StudentGet")]
        public ActionResult Edit(byte? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
[Route("~/stu-info/edit-info")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "StudentId,LirstName,LastName,Age,SchoolName")] Student student)
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }

我试过更改@Html.ActionLink中的第二个参数,它可以更改URL(我不知道如何更改 Students 参数)但是没有成功,因为也许它没有识别编辑操作。

到达它的最简单方法是使用属性路由

[Route("~/stu-info/get-info/{id?}" Name="StudentGet")]
public ActionResult Edit(byte? id)
......
  
[Route("~/stu-info/edit-info" )]
public ActionResult Edit(Student student)
.....

也许您需要更改您的操作链接以获取更多

 @Html.RouteLink("Edit", "StudentGet", new { id=item.StudentId }) 

并将 MapMvcAttributeRoutes 添加到您的路由配置中

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

             routes.MapMvcAttributeRoutes();
           ......
}

到达它的最简单方法是使用属性路由

[路线(“登录”)]

public ActionResult Login(string ReturnUrl = "")