Url.Action map a wrong link from Route attribute

2020-04-03 06:51发布

This is target controller and action:

[RoutePrefix("Editor")]
public class EditorController : Controller

[HttpGet]
    [Route("{id:int}")]
    public ActionResult Edit(int id)

Map method calling:

@Url.Action("Edit", "Editor", new { id = page.Id})

result: /Editor?id=1

required result: /Editor/1

标签: asp.net-mvc
3条回答
看我几分像从前
2楼-- · 2020-04-03 07:31

To achieve the result you want you have to use a route name:

[HttpGet]
[Route("{id:int}", Name = "EditorById")]
public ActionResult Edit(int id)

Then in your view you would use Url.RouteUrl instead of Url.Action:

@Url.RouteUrl("EditorById", new { controller = "Editor", Id = 1, action = "Edit" })

Hope this helps,

查看更多
狗以群分
3楼-- · 2020-04-03 07:37

I just faced with same problem. When i fixed the links - editing is broken (form always redirects to the same page).

Here is solution:

A link

@Html.ActionLink("Edit my nice object", "Edit", new { id=item.Id })

A form in the view Edit.cshtml (specifying Controller name is necessary!)

@using (Html.BeginForm("EditConfirmed", "AppServers"))

The actions in the controller

public class AppServersController         
    [Route("edit/{id:int?}")]
    public ActionResult Edit(int? id)
    {
        // bla-bla
    }
    [Route("edit_confirmed")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult EditConfirmed([Bind(Exclude = "Created,LastModified")] AppServerVM appServer)
    {
        if (!ModelState.IsValid) return View("Edit", appServer);
        // bla-bla
    }
}

Now both links and editing works.

查看更多
爷、活的狠高调
4楼-- · 2020-04-03 07:39

Have you checked if you have enabled MVC AttributeRoutes?

routes.MapMvcAttributeRoutes();

see http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

查看更多
登录 后发表回答