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

ris*_*ism 16 c# asp.net-mvc razor asp.net-mvc-4

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

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

我正在做的就是控制器:

[AllowAnonymous]
public ActionResult Register()
{
    ViewBag.IsRegistration = true;
    return View();
}
Run Code Online (Sandbox Code Playgroud)

然后在视图中:

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

但它失败了:

@if (ViewBag.IsRegistration)
Run Code Online (Sandbox Code Playgroud)

UPDATE

相关控制器代码:

[AllowAnonymous]
public ActionResult Register()
{
    ViewBag.IsRegistration = "true";
    return View();
}
Run Code Online (Sandbox Code Playgroud)

注册视图:

@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")
}
Run Code Online (Sandbox Code Playgroud)

ExternalLoginsList部分:

@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>
    }
}
Run Code Online (Sandbox Code Playgroud)

acf*_*cis 53

尝试:

@if (ViewBag.IsRegistration == true)
Run Code Online (Sandbox Code Playgroud)

  • 最简单,最快速的解决方案. (4认同)
  • 您不必检查null,因为`null == true`正确评估为`false`。没有`== true`,对于'@if'条件,空值将不是有效值。 (2认同)
  • 有趣的解决方案。我可以看到的唯一缺点是另一个开发人员可能不明白为什么会出现这种情况,并且可能认为删除 == true 作为对代码的快速简化 (2认同)

jfr*_*484 17

我知道这是一个老问题,但我想我有一个优雅的答案,所以如果有人在搜索后读到这个,这是我的:

@if (ViewBag.IsRegistration ?? false)
Run Code Online (Sandbox Code Playgroud)