[英]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.如果
string
类型传递给View()
调用而不转换为object
,它将被解释为视图名称。
And the view model data should be declared as视图 model 数据应声明为
@model string;
<h2>@Model</h2>
Try changing the route as given below -尝试如下所示更改路线 -
[Route("Books", Name = "id")] [路线(“书籍”,名称=“id”)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.