2012-08-07 95 views
0

我的网址如下:为什么我的MVC ID返回Null(或Nothing)?

{控制器}/{行动}/{ID}

在这个例子中,它是:

博客/编辑/ 2

在我的代码,我想获得的ID参数(这是“2”),像这样:

' get route 
Dim routeData = httpContext.Request.RequestContext.RouteData 
' get id 
Dim id = If(String.IsNullOrEmpty(routeData.Values("id") = False), routeData.Values("id").ToString, Nothing) 

然而,跟它的价值是空的。下面的语句由于某种原因,返回true:

If String.IsNullOrEmpty(id) = True Then 

我怎样才能获得ID的值,使之不为NULL(或VB.NET“无”)?

+1

在你的代码你在哪里做? – Oded 2012-08-07 15:14:14

+0

这是发生在授权Atttribute如下所示http://stackoverflow.com/questions/11847262/stackoverflowexception-was-unhandled-in-customauthorize-authorizeattribute – user1477388 2012-08-07 15:16:05

回答

1

解决的办法是改变我用的是IsNullorEmpty方法:

' get id 
    Dim id = If(String.IsNullOrEmpty(routeData.Values("id")), Nothing, routeData.Values("id").ToString) 

    ' if no id is set, check to see if the user owns the requested entity (company or blog) 
    If String.IsNullOrEmpty(id) Then 
1

它不返回任何。

你原来的职位读取String.IsNullOrEmpty(routeData.Values("id") = False) - 你的右括号是放错了地方,所以String.IsNullOrEmpty将总是返回FALSE。你应该写String.IsNullOrEmpty(routeData.Values("id")) = False

(在VB中,"xyz" = false将隐式转换为"False"。)

+0

谢谢,丹。我正在使用我自己的解决方案,但您的解决方案也可能是正确的(可能更正确)。 – user1477388 2012-08-07 15:34:43

+0

你的新代码更简洁(不需要隐式的'= False'),但我想强调为什么你的原始代码不合格。 – 2012-08-07 15:41:13