Unable to get the value of Enum from asp-route-data

184 Views Asked by At

I have an enum:

public enum mediaType
{        
    Video = 0,
    Voice = 1,
    Image = 2
}

Now I want to pass a value from view to controller by using Tag Helper.

<a class="btn btn-primary" asp-controller="ShowMedia" asp-action="Index" asp-route-typeindex="mediaType.Video">All Video</a>

and in Controller

public IActionResult Index(mediaType typeindex=mediaType.Image)
{
    //does something
    return View(typeindex.ToString(), model);
}

The problem is that typeindex parameter is always filled with its default value: mediaType.Image and it never gets the value for asp-route-typeindex="mediaType.Video".

1

There are 1 best solutions below

0
On BEST ANSWER

Inspect the HTML element, you would see you are passing a string "mediaType.Video" but not an Enum value.

enter image description here

In the controller, the Index will use the default value mediaType.Image

You need a @ syntax to use the variable/value which is from Razor.

<a class="btn btn-primary" asp-controller="ShowMedia" asp-action="Index" 
    asp-route-typeindex="@mediaType.Video">All Video</a>

enter image description here


Aside, would suggest naming mediaType with Pascal case for the naming conventions.

public enum MediaType
{        
    Video = 0,
    Voice = 1,
    Image = 2
}