在ASP.NET MVC中加载ViewBag [英] Loading ViewBag in ASP.NET MVC

查看:59
本文介绍了在ASP.NET MVC中加载ViewBag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET MVC应用程序.我有几个依赖于相同数据的视图.因此,我想在控制器中创建一个共享函数来填充ViewBag.目前,我正在尝试以下操作:

I am working on an ASP.NET MVC app. I have several views that rely on the same data. For that reason, in my controller, I thought I would create a shared function to populate the ViewBag. Currently, I'm trying the following:

public async Task<ActionResult> Create()
{
  await LoadViewBag();
  return View();
}

public async Task<ActionResult> Edit(int id)
{
  await LoadViewBag();
  return View();
}

private async Task<bool> LoadViewBag()
{
  ViewBag.PossibleTypes = await MyType.GetAllFromDatabase();
  ViewBag.PossibleContacts = await Contact.GetAllFromDatabase();
  ViewBag.InvitedBy = GetFullName();

  return true;
}

在我看来,我有:

@Html.Raw(ViewBag.InvitedBy)

不幸的是,视图中从不显示放入InvitedBy的值.我设置了一个断点,看起来好像已正确设置了它.我在做什么错了?

Unfortunately, the value put into InvitedBy is NEVER shown in the view. I set a breakpoint and it looks like its being set properly. What am I doing wrong?

推荐答案

ViewBag 的值仅适用于当前请求.您的代码确实被重定向到 async Task 来设置ViewBag的值.因此,您为 ViewBag 设置的值将与该请求一同消失.

The value for the ViewBag only lives for the current request. You code does gets redirected to an async Task to set the values for the ViewBag. So the value you set for the ViewBag will die along with that request.

相反,如果您在相应的ActionResult中设置ViewBag的值而不是共享函数,则该ViewBag将保留并在视图中获取该值.

Rather if you set the values for the ViewBag in the respective ActionResult instead of a shared function then it will survive and you will get the value in the view.

您可以考虑改用 TempData . TempData 在内部使用Session来存储值.

You may consider using TempData instead. TempData internally uses the Session to store the value.

private async Task<bool> LoadViewBag()
{
  ...
  ...
  TempData["InvitedBy"] = GetFullName();

  return true;
}

然后在您认为可以使用的情况下

Then in you view you can use

@if (TempData["InvitedBy"] != null)
{
   @Html.Raw(@TempData["Message"])
}

这篇关于在ASP.NET MVC中加载ViewBag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆