2

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

1
  • Test is the controller name. Basically I want to call the Index method of my Controller Test with an optional parameter Commented Aug 14, 2020 at 12:59

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

But it doesnt work, she site is callable with the following url "localhost:6002/Test/Index/<id>" but I do not want the Index inside the url. My routing is set up like this in my startup app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Status}/{action=Index}/{id?}"); }); Which is for another controller. I've tried to add something similar for my controller but it didnt change anything.
3

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

        });

1 Comment

I still need to do "Test/Index/<id>", ive tried something similar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.