1

I am trying to add a single link in my navbar that redirects the user to a different webpage depending on their account type. I am having issues doing this and could use some help.

The Controller code that I am calling looks like this:

public IActionResult Attendance(char accountType)
{
     if (accountType.Equals("m") || accountType.Equals("a"))
     {
          return RedirectToAction("FacultyAttendance");
     }
     else
     {
          return RedirectToAction("StudentAttendance");
     }
}

public IActionResult StudentAttendance()
{
     // More functionality will be added later
     return View();
}

public IActionResult FacultyAttendance()
{
     // More functionality will be added later
     return View();
}

Following this answer for calling the Controller method, I have this code snippet in the View file:

<a href="<%: @Url.Action("Attendance", "HomeController", new {accountType = "m"}) %>">Attendance</a>

This gives me the following error:

Bad Request - Invalid URL

HTTP Error 400. The request URL is invalid.

I also tried following this answer by removing the <%: and %>.

<a href="@Url.Action("Attendance", "HomeController", new {accountType = "m"})">Attendance</a>

If I do this, I just get blank webpage.

My first problem lies in which style I should use for this method call within the View file. Are either of these correct, or should I use something else entirely? Might the issue be with the way I have the Controller code set up?

Any help would be appreciated, as I am new to the MVC framework for ASP.NET.

Edit: The solution I found is a bit different than what I originally posted. I used this tag in my View and got it to work:

<a asp-controller="Home" asp-action="Attendance" asp-route-accountType='s'>Attendance</a>

I also followed ThisGuy's suggestions for improving the code since I had mismanaged some variables and that may have been part of the problem.

Community
  • 1
  • 1
acbarker15
  • 15
  • 5

1 Answers1

0

accountType is a char, but you are passing a string:

new {accountType = "m"}

Change the Controller to take a string instead of char for accountType.

public IActionResult Attendance(string accountType)

Also, I'd write it like this:

public IActionResult Attendance(string accountType) => 
    RedirectToAction(
        accountType.Equals("m") || 
        accountType.Equals("a") 
            ? nameof(FacultyAttendance)
            : nameof(StudentAttendance));
ThisGuy
  • 2,335
  • 1
  • 28
  • 34
  • Nice catch on the string vs char. I updated that to be the correct data type. Thank you for the alternate way to set up the comparison, I think I may use that. However, neither of those changes fixed the issue I'm having. I still get an HTTP Error 400 code from clicking the link that calls the method. – acbarker15 Apr 03 '20 at 23:06
  • It should be "Home" not "HomeController" as well. – ThisGuy Apr 04 '20 at 05:56