Mvc ViewBag - 无法将null转换为'bool',因为它是一个不可为空的值类型

时间:2013-10-23 22:26:30

标签: c# asp.net-mvc asp.net-mvc-4 razor

我想在生成某个视图时在控制器中将bool设置为true,然后相应地更改视图的标题。这应该是简单的,但我得到:

  

无法对空引用执行运行时绑定异常详细信息:   Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:无法执行   对空引用的运行时绑定

我所做的一切都在控制器中:

   [AllowAnonymous]
        public ActionResult Register()
        {
            ViewBag.IsRegistration = true;
            return View();
        }

然后在视图中:

 @if (ViewBag.IsRegistration)
        {
        <legend>Register using another service.</legend>
        }
        else
        {
        <legend>Use another service to log in.</legend>
        }

但它失败了:

@if (ViewBag.IsRegistration)

更新

相关控制器代码:

[AllowAnonymous]
public ActionResult Register()
{
    ViewBag.IsRegistration = "true";
    return View();
}

注册视图:

@model Mvc.Models.RegisterViewModel
@{
    Layout = "~/Views/Shared/_AccountLayout.cshtml";
    ViewBag.Title = "Register";
}

<hgroup class="title">
    <h1>@ViewBag.Title.</h1>
</hgroup>

<div class="row">
<div class="col-lg-6">
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary()

        <fieldset class="form-horizontal">
            <legend>Create a new account.</legend>
            <div class="control-group">
                @Html.LabelFor(m => m.UserName, new { @class = "control-label" })
                <div class="controls">
                    @Html.TextBoxFor(m => m.UserName)
                </div>
            </div>
            <div class="control-group">
                @Html.LabelFor(m => m.Password, new { @class = "control-label" })
                <div class="controls">
                    @Html.PasswordFor(m => m.Password)
                </div>
            </div>
            <div class="control-group">
                @Html.LabelFor(m => m.ConfirmPassword, new { @class = "control-label" })
                <div class="controls">
                    @Html.PasswordFor(m => m.ConfirmPassword)
                </div>
            </div>
            <div class="form-actions no-color">
                <input type="submit" value="Register" class="btn" />
            </div>
        </fieldset>
    }
</div>
    <div class="col-lg-6"></div>
  <section id="socialLoginForm">
            @Html.Action("ExternalLoginsList", new { ReturnUrl = ViewBag.ReturnUrl })
        </section>
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

ExternalLoginsList partial:

@using Glimpse.Core.Extensions
@using Microsoft.Owin.Security
@model ICollection<AuthenticationDescription>

@if (Model.Count == 0)
{
    <div class="message-info">
        <p>There are no external authentication services configured</p>
    </div>
}
else
{
    using (Html.BeginForm("ExternalLogin", "Account", new { ReturnUrl = ViewBag.ReturnUrl }))
    {
    @Html.AntiForgeryToken()

        <fieldset id="socialLoginList">
            @if (!string.IsNullOrEmpty(ViewBag.IsRegistration))
            {
            <legend>Register using another service.</legend>
            }
            else
            {
            <legend>Use another service to log in.</legend>
            }
            <p>
                @foreach (AuthenticationDescription p in Model) {
                    <button type="submit" class="btn" id="@p.AuthenticationType" name="provider" value="@p.AuthenticationType" title="Log in using your @p.Caption account">@p.AuthenticationType</button>
                }
            </p>
        </fieldset>
    }
}

7 个答案:

答案 0 :(得分:49)

尝试:

@if (ViewBag.IsRegistration == true)

答案 1 :(得分:1)

试试这个:

替换控制器中的行:

ViewBag.IsRegistration = true;

ViewBag.IsRegistration = new bool?(true);

并替换视图中的行:

@if (ViewBag.IsRegistration)

@if ((ViewBag.IsRegistration as bool?).Value)

实际上,你可以在ViewBag中放置一个可以为空的bool,然后展开它。

答案 2 :(得分:1)

在检查null之前,只需检查true

if (ViewBag.IsRegistration != null && ViewBag.IsRegistration)

答案 3 :(得分:1)

好的,根据评论中的Floods建议,我需要传递参数。父视图中的ViewBag不会流向部分视图。

因此,在注册视图的代码中,我需要从

进行更改
 <section id="socialLoginForm">
       @Html.Action("ExternalLoginsList", new {ReturnUrl = ViewBag.ReturnUrl})
 </section>

<section id="socialLoginForm">
    @Html.Action("ExternalLoginsList",
            new {ReturnUrl = ViewBag.ReturnUrl,
                 IsRegistering = @ViewBag.IsRegistering })
</section>

然后进入我的帐户控制器并从以下地址更改:

[AllowAnonymous]
[ChildActionOnly]
public ActionResult ExternalLoginsList(string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;
    return (ActionResult)PartialView("_ExternalLoginsListPartial", new List<AuthenticationDescription>(AuthenticationManager.GetExternalAuthenticationTypes()));
}

[AllowAnonymous]
[ChildActionOnly]
public ActionResult ExternalLoginsList(string returnUrl, string isRegistering) {
   ViewBag.IsRegistering = (isRegistering.ToLower() == "true");
   ViewBag.ReturnUrl = returnUrl;
   return (ActionResult)PartialView("_ExternalLoginsListPartial", new List<AuthenticationDescription>(AuthenticationManager.GetExternalAuthenticationTypes()));
}

然后在ExternalLogins中我可以:

@if (ViewBag.IsRegistering)
必要时。

因此,我有效地将IsRegistering bool从控制器传递到主视图,然后返回到控制器上的操作方法,然后返回ViewBag,这允许我访问子部分视图中的bool。

非常感谢。

答案 4 :(得分:0)

Viewbag中的布尔人总是很棘手。试试这个

[AllowAnonymous]
        public ActionResult Register()
        {
            ViewBag.Registration = "x";//x or whatever
            return View();
        }

@if (!String.IsNullorEmpty(ViewBag.Registration))
        {
        <legend>Register using another service.</legend>
        }
        else
        {
        <legend>Use another service to log in.</legend>
        }

答案 5 :(得分:0)

尝试使用TempData而不是ViewBag。

更改您的代码

控制器

ViewBag.IsRegistration=true;

TempData["IsReg"]=true;

并在视图中

@if((bool)TempData["IsReg"])

您似乎正在使用子部分视图中的值,并且您正在父操作中添加数据.Viewbag中的值无法将数据从一个操作传递到其他操作的视图。 TempData使用会话时,可以使用它将数据传递给另一个动作视图。

答案 6 :(得分:0)

也许是这样:

@if ((ViewBag.IsRegistration != null) && (ViewBag.IsRegistration is bool) && (bool)ViewBag.IsRegistration)
{
}