user9491184
user9491184

Reputation:

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

Upvotes: 2

Views: 4060

Answers (2)

Samy K. Abushanab
Samy K. Abushanab

Reputation: 46

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://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-3.1

Upvotes: 3

Badran Yahyaoui
Badran Yahyaoui

Reputation: 81

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?}");

        });

Upvotes: 3

Related Questions