gpt4 book ai didi

c# - 无法对空引用执行运行时绑定(bind)。 ViewBag.Title 为空

转载 作者:太空狗 更新时间:2023-10-30 01:18:15 24 4
gpt4 key购买 nike

我想提供一个简单的通用功能,以便在我需要通知用户操作成功时在页面顶部显示一条消息。我的解决方案是将一个对象放入 ViewBag.Info包含有关消息的详细信息,包括 bool public IsMessage;并在 _Layout.cshtml 中阅读我有一个额外的隐藏 div .

我在 _Layout.cshtml 中尝试的方式是我把什么放在 @(ViewBag.Info.IsMessage 里吗? (false/true) 到隐藏字段并通过 JavaScript 读取它。如果该字段包含“true”,javascript 将调用函数 ShowEvent() .

出于某种原因,如果我添加行 @(ViewBag.Info.IsMessage.ToString().ToLower()) VS2010 提示 ViewBag.Title_Layout.cshtml .

"Cannot perform runtime binding on a null reference"

_Layout.cshtml的代码很简单:

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<link rel="Stylesheet" type="text/css" href="@Url.Content("~/Content/StyleSheet.css")" />
<script src="~/Scripts/jquery-2.1.1.min.js" type="text/javascript"></script>
<title>@ViewBag.Title</title>
</head>
<body>
<input type="hidden" id="is-event" name="is-event" value="@(ViewBag.Info.IsMessage.ToString().ToLower())"/>
<div class="recent-events"></div>
<div>
@if (IsSectionDefined("loginfo"))
{
@RenderSection("loginfo", false)
}
@RenderBody()
@if (IsSectionDefined("Home"))
{
@RenderSection("Home", false)
}
</div>
</body>
</html>

以及 View 的代码Index.cshtml是:

@model TestProject.ViewModels.Account.UserData
@{
ViewBag.Title = "Index";
string identityName = HttpContext.Current.User.Identity.Name;
string userrole = Model.UserRoles.FirstOrDefault();
}

<h2>Index</h2>
<br />

如你所见ViewBag.Title已定义。

编辑。 Controller 代码:

public ActionResult Index()
{
// ...
InfoModel infoModel = new InfoModel()
{
IsMessage = true, Duration = 3000, Message = "Logging in successfull", BackgroundColor = "#bbffbb"
};
ViewBag.Info = infoModel;
ViewBag.Title = string.Empty;
return View(userdata);
}

最佳答案

如果您尝试从非强类型 View 引用模型,就会遇到此问题。例如,输入

@Model.ID 

页面中的某处将尝试绑定(bind)到 ViewModel 的 ID 属性 - 如果您尚未在 View 页面顶部定义模型类型

@model MyModel 

然后它会用这个模糊的错误消息轰炸。

关于c# - 无法对空引用执行运行时绑定(bind)。 ViewBag.Title 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28147460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com