简体   繁体   中英

ASP.NET MVC Attribute routing parameter issue

I have the following code

public class BooksController : Controller
{
    [Route("/Books/{id?}")]
    public IActionResult Index(string id)
    {
        return View(id);
    }
}

My problem is that when I try to enter the parameter it is (as it seems) considered as controller's action so I keep getting this exception.

例外

I need somebody to explain what am I doing wrong.

If you want to pass some parameter to a view as a string you can make this like below:

public class BooksController : Controller
{
    [Route("/Books/{id?}")]
    public IActionResult Index(string id)
    {
        if (string.IsNullOrEmpty(id))
            id = "default_value";
        return View((object)id);
    }
}

If the string type is passing to the View() call without casting to object it will be interpreted as a view name.

And the view model data should be declared as

@model string;
<h2>@Model</h2>

Try changing the route as given below -

[Route("Books", Name = "id")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM