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.
CodePudding user response:
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>
CodePudding user response:
Try changing the route as given below -
[Route("Books", Name = "id")]