Asp.net core mvc optional parameter for Index

im currently trying to create a Controller in ASP.net core mvc with an optional parameter “id”.
Im fairly new to asp.net, I’ve tried to check other posts but nothing solved my problem.

public class TestController : Controller
{
    private readonly ITestRepository _TestRepository;

    public TestController(ITestRepository TestRepository)
    {
        _TestRepository = TestRepository;
    }

    public async Task<IActionResult> Index(string id)
    {
        if (string.IsNullOrEmpty(id))
        {
            return View("Search");
        }
        var lieferscheinInfo = await _TestRepository.GetTestdata(Convert.ToInt64(id));
        if (lieferscheinInfo == null)
        {
            // return  err view
            throw new Exception("error todo");
        }
        return View(lieferscheinInfo);

    }
}

I want to open the site like this “localhost:6002/Test” or “localhost:6002/Test/123750349” e.g, the parameter can be an int as well, i’ve tried both(string and int) but it doesnt work.
Either the site returns 404 (for both cases, with and without an parameter) or the parameter gets ignored and is always null.
I’ve tried to add [Route("{id?}")] on the Index but it did not change anything.

Greetings

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In your project’s Startup class make sure you are using the right MapControllerRoute

 app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Test}/{action=Index}/{id?}");

        });

Method 2

your code should work just fine. string parameters accepts null by default so you dont need to specify can you check how the routing is set up in your startup.cs file.

You can add routing through attribute for example the following :

[Route("Test")]
[Route("Test/Index")]
[Route("Test/Index/{id?}")]

Will allow you to access the Action using :

/test/?id=sasasa
test/Index/?id=sasasa 
test/Index

check Routing Documentation at Microsoft site :
https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-3.1

Method 3

Update the MapControllerRoute in the Startup.cs

app.UseEndpoints(endpoints => {
     endpoints.MapControllerRoute(
         name : "default",
         pattern: "{controller=Test}/{action=Index}/{id?}"
     );
});


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x