当我为ViewBag分配一个可以为空的整数时,它会使值无法取消?

Mik*_*ron 5 c# asp.net-mvc nullable asp.net-mvc-5

考虑这个ASP.NET MVC 5控制器:

public class MyController : Controller {
    public ActionResult Index(int? id) {
        ViewBag.MyInt = id;
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

而这种观点:

<p>MyInt.HasValue: @MyInt.HasValue</p>
Run Code Online (Sandbox Code Playgroud)

当我调用URL /my/(具有空id)时,我得到以下异常:

An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code

Additional information: Cannot perform runtime binding on a null reference
Run Code Online (Sandbox Code Playgroud)

相反,如果我在(例如/my/1)中传递ID :

An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code

Additional information: 'int' does not contain a definition for 'HasValue'
Run Code Online (Sandbox Code Playgroud)

这对我来说这ViewBag.MyInt不是一种类型Nullable<int>,而是一种int或两种类型null.

这是ViewBag这样做的吗?或者,像这样的拳击Nullable类型是否更为基础?或者是其他东西?

还有另一种方法吗?

(我想我可以改变我的支票ViewBag.MyInt == null,但是让我假装我Nullable出于某种原因需要一种类型)

Ben*_*aul 3

我建议您创建一个视图模型,该模型将为您提供充分的灵活性,使“MyInt”成为可为空的类型。

当然,另一种选择是仅在“MyInt”不为空时设置它......

public class MyController : Controller {
    public ActionResult Index(int? id) {
        if (id.HasValue)
        {
            ViewBag.MyInt = id;
        }
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

看法:

@if (ViewBag.MyInt != null)
{
    <p>Has an Id</p>
}
else
{
    <p>Has no Id.</p>
}
Run Code Online (Sandbox Code Playgroud)

就我个人而言,我会选择视图模型,因为它是最佳实践,我很少使用 ViewBag,除非它用于非常简单的场景。