ASP.NET MVC3:列表和详细信息视图具有相同名称和不同参数的 ActionMethod
我有一个 ProdcutsController,其中有 2 个操作方法。索引和详细信息。 Index 将返回产品列表,Details 将返回所选产品 ID 的详细信息。
所以我的网址就像
sitename/Products/
将加载索引视图以显示产品列表。
sitename/Products/Details/1234
将加载详细信息视图以显示产品 1234 的详细信息。
现在我想避免第二个网址中的“详细信息”一词。这样看起来就像
sitename/Products/1234
我尝试将操作方法从“详细信息”重命名为“索引”,其中包含一个参数。但它向我显示错误“方法不明确
”
我尝试了这个
public ActionResult Index()
{
//code to load Listing view
}
public ActionResult Index(string? id)
{
//code to load details view
}
,现在收到此错误
The type 'string' must be a non-nullable value type in order to use
it as parameter 'T' in the generic type or method 'System.Nullable<T>
意识到它不支持方法重载!我该如何处理这个问题?我应该更新我的路线定义吗?
I have a ProdcutsController where i have 2 Action methods. Index and Details.
Index will return list of products and Details will return details of a selected product id.
So my urls are like
sitename/Products/
will load index view to show a list of products.
sitename/Products/Details/1234
will load details view to show the details of product 1234.
Now i want to avoid the "Details" word from my second url. so that it should look like
sitename/Products/1234
I tried to rename my action method from "Details" to "Index" with a parameter in it. But it showed me the error "Method is is ambiguous
"
I tried this
public ActionResult Index()
{
//code to load Listing view
}
public ActionResult Index(string? id)
{
//code to load details view
}
I am getting this error now
The type 'string' must be a non-nullable value type in order to use
it as parameter 'T' in the generic type or method 'System.Nullable<T>
Realized that it does not support method overloading ! How do i handle this ? should i update my route definition ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用这个:
假设该值是整数类型。
这是另一种选择:
string
是一种引用类型,因此可以将null
分配给它,而无需Nullable
。Use this:
Assuming the value is an integer type.
This is another option:
A
string
is a reference type so anull
can already be assigned to it without needing aNullable<T>
.您可以只使用一种 Action 方法。
像这样的东西:
You can just use one Action method.
Something like:
您可以创建两个路由并使用路由约束:
Global.asax
第一个路由有一个约束,要求 id 具有一个或多个数字。由于这个限制,它不会捕获像
~/home/about
等路由。
You can create two routes and use route constraints:
Global.asax
First route has a constraint that requires id to have one or more digits. Because of this constraint it won't catch routes like
~/home/about
etc.ProductsController