MVC6 attribute routing with two parameters

前提是你 提交于 2019-12-12 20:39:58

问题


I've had a look around for this and nothing that pertains to the MVC6 taghelper anchor tag in relation to having an alternative [HttpGet] method that caters for multiple parameters.

Sure you can add multiple parameters to a MVC6 anchor taghelper but how do you process the second option with two parameters using attrubute routing...

I have two [HttpGet] IactionResult methods:

    //GET: UserAdmin
    public async Task<IActionResult> Index()
    {
        return View(await _userAdminService.GetAllUsers("name_desc", false));
    }


    // GET: UserAdmin/name_desc/True
    [HttpGet("Index/{sortValue}&{showDeactivated}")]
    public async Task<IActionResult> Index(string sortValue, bool showDeactivated)
    {
        return View(await _userAdminService.GetAllUsers(sortValue, showDeactivated));
    }

I have in my view an attempt to go to the second method:

<a asp-action="Index" asp-route-sortValue="@Model.DisplayName" asp-route-showActivated="@Model.ShowDeActivated">Name: <span class="glyphicon glyphicon-chevron-down"></span></a>

which renders to:

<a href="/UserAdmin?sortValue=name showActivated=True">Name: <span class="glyphicon glyphicon-chevron-down"></span></a>

or

    localhost.../UserAdmin?sorValue=name&showActivated=True

IT never goes to the second method.

What do I need to do to use the second [HttpGet] method with two parameters using the MVC6 anchor taghelper?

EDIT

Also how do you handle the ampersand separating the two parameters in the route attribute...


回答1:


There is no support for ampersand in route template. The idea is that ampersand is used for query string and it will always be applied to any route template. That's why your second action is never called.

For example you can change your route template to [HttpGet("UserAdmin/Index/{sortValue}/{showDeactivated}")]

Official documentation link




回答2:


Don't split up your actions in this case. You can just as easily do this in one action:

public async Task<IActionResult> Index(string sortValue, bool showDeactivated)
{
    var sort = string.IsNullOrWhiteSpace(sortValue) ? "name_desc" : sortValue;

    return View(await _userAdminService.GetAllUsers(sort, showDeactivated));
}

If the sortValue GET parameter is not supplied it will default to null, and if showDeactivated is not supplied it will default to false.




回答3:


Latest version of ASP.NET Core can handle this:

[HttpGet("Index")]
public async Task<IActionResult> Index([FromQuery(Name ="sortValue")]string sortValue,[FromQuery(Name ="showDeactivated")] bool showDeactivated)


来源:https://stackoverflow.com/questions/37063448/mvc6-attribute-routing-with-two-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!