Warm tip: This article is reproduced from serverfault.com, please click

Have 2 Different IActionResults, one with a parameter and one without a parameter

发布于 2020-11-30 11:14:27

I want to have to different IActionResults like this.

[HttpGet]
public IActionResult CreateTournament()
    {
        ViewData["Creator"] = "User";
        TournamentDTO tournamentDTO = new TournamentDTO()
        {
            OrganisationID = "null",
        };
        return View();
    }

[HttpGet]
public IActionResult CreateTournament(string OrganisationID)
    {
        ViewData["Creator"] = "Org";
        TournamentDTO tournamentDTO = new TournamentDTO()
        {
            OrganisationID = OrganisationID,
        };
        return View();
    }

But when I try to navigate to this page it gives an error

AbiguousMatchException: The request matched multiple endpoints. Matches: F4DEDTournaments.Controllers.TournamentController.CreateTournament (F4DEDTournaments) F4DEDTournaments.Controllers.TournamentController.CreateTournament (F4DEDTournaments)

Is there a fix for this without putting both codeblocks in the same method like this?

[HttpGet]
public IActionResult CreateTournament(string OrganisationID)
    {
        if( OrganisationID == string.empty)}
        {
            ViewData["Creator"] = "User";
            TournamentDTO tournamentDTO = new TournamentDTO()
            {
                OrganisationID = "null",
            };
            return View();
        } else {
            ViewData["Creator"] = "Org";
            TournamentDTO tournamentDTO = new TournamentDTO()
            {
            OrganisationID = OrganisationID,
            };
            return View();
        }
    }
Questioner
Tijn van Veghel
Viewed
0
user11646156 2020-11-30 19:23:38

The action params are optional by default, so i would prefer one method:

[HttpGet]
public IActionResult CreateTournament(string OrganisationID)
    {
        ViewData["Creator"] = OrganisationID == null? "Org" : "User";
        TournamentDTO tournamentDTO = new TournamentDTO()
        {
            OrganisationID = OrganisationID == null? "null" : OrganisationID
        };
        return View();
    }