可以将 Guid 作为 asp.net mvc 3 控制器操作中的可选参数吗?
我试图在控制器上执行索引操作,以选择性地采用像这样的 guid:
public ActionResult Index(Guid id = default(Guid))
或像这样
public ActionResult Index(Guid id = new Guid())
我希望利用 C# 的可选参数,并且我的路线也定义了可选参数:
routes.MapRoute(
"Default", "{controller}/{action}/{id}",
new { controller = "somecontroller", action = "Index", id = UrlParameter.Optional }
但是调用“somecontroller/index”会给出以下结果错误...
参数字典包含一个 参数“id”的条目为空 不可为 null 的类型“System.Guid” 方法'System.Web.Mvc.ActionResult 索引(System.Guid)' in '控制器.SomeController'。 可选参数必须是 引用类型、可为 null 的类型,或者是 声明为可选参数
是不可能的吗?我缺少什么?谢谢
I was trying to have an index action on a controller to optionally take a guid like so:
public ActionResult Index(Guid id = default(Guid))
or like so
public ActionResult Index(Guid id = new Guid())
I was hoping to take advantage of C#'s optional parameters and my routes are also defined optional parameters:
routes.MapRoute(
"Default", "{controller}/{action}/{id}",
new { controller = "somecontroller", action = "Index", id = UrlParameter.Optional }
but calling "somecontroller/index" gives following error...
The parameters dictionary contains a
null entry for parameter 'id' of
non-nullable type 'System.Guid' for
method 'System.Web.Mvc.ActionResult
Index(System.Guid)' in
'Controllers.SomeController'.
An optional parameter must be a
reference type, a nullable type, or be
declared as an optional parameter
is it just not possible? What am I missing? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Guid 不可为空。例如,您不能这样做
但是,在 C# 2 中,添加了一些语法糖以使值类型可以为 null(通过将它们包装在 Nullable 对象中),如下所示:
鉴于该规则,让我们看一下您的路线
:如果您在路由中指定
id
参数是可选的,则必须使用可以为null
的类型,或 您必须完全省略该参数在你的行动中。因此,要修复您的操作,您需要将Guid id
参数更改为Guid? id
它应该可以工作。之后,您可以检查该值以确保它不为空,如下所示:A Guid is not nullable. For example you can't do this
However, in C# 2, some syntactic sugar was added to make value types nullable (by wrapping them in a Nullable object), like so:
Given that rule, let's take a look at your route:
Since you specified in your route that the
id
parameter is optional, you must use a type that can benull
, or you must omit the parameter completely in your action. So to fix your action, you need to change theGuid id
parameter to beGuid? id
and it should work. After that, you can check the value to make sure it's not null like so: