【问题标题】:@ViewBag getting null value from UserProfile@ViewBag 从 UserProfile 获取空值
【发布时间】:2014-10-11 19:30:04
【问题描述】:

我在将值从UserProfile 传递到@Viewbag 以显示在Index.cshtml 中时遇到一些问题。

让我们解释一下

当我注册新用户或登录时,我试图在 viewbag 中从 UserProfile 传递 UserType 字段。 UserType 是我在UserProfile 上创建的自定义字段,用于验证用户是“Musico”还是“Ouvinte”

调试应用程序后,我看到 viewbag 正在取 NULL 值。

这是我试图从UserProfile 中的Register and Login post method 中获取价值的代码:

登录后方法

[HttpPost] 
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid && WebSecurity.Login(model.UserName,
                                                model.Password,
                                                persistCookie: model.RememberMe))
    {
        var context = new UsersContext();
        var username = User.Identity.Name;
        var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username);
        var userType = user.UserType;

        TempData["UserType"] = userType; //Taking UserType from User Profile
        return RedirectToLocal(returnUrl);
    }

    // If we got this far, something failed, redisplay form
    ModelState.AddModelError("", "The user name or password provided is incorrect.");
    return View(model); 
}

注册发布方法

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {
            var context = new UsersContext();
            var username = User.Identity.Name;
            var user = context.UserProfiles
                              .SingleOrDefault(u => u.UserName == username);
            var userType = user.UserType;
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new
            {
                UserType = model.UserType
            });
            WebSecurity.Login(model.UserName, model.Password);

            // string currentUserType = u.UserType;                    
            TempData["UserType"] = userType;//Get the userType to validate on _Layout
            return RedirectToAction("Index", "Home");
        }
        catch (MembershipCreateUserException e)
        {
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
    }
    return View(model);
}

在索引页面的一部分调用viewbag

<p>
@if (Request.IsAuthenticated && ViewBag.UserType.Equals("Musico")) 
         {
              <span>musico</span>
         }
         else if (Request.IsAuthenticated && ViewBag.UserType.Equals("Ouvinte"))
         {
             <span>ouvinte</span>
         } else{
          <span>teste</span>
         }
</p>

HomeController

public ActionResult Index()
{
    ViewBag.UserType = TempData["UserType"];
    return View();
}

【问题讨论】:

  • @Silvermind 你能举个例子吗?对不起,我不明白你的想法
  • 查看Index.cshtml 我第一次运行应用程序时,页面上会显示“teste”。在我登录应用程序后,索引上有断点,值为空,我会放一个屏幕imgur.com/upOyyq7
  • 当我登录时,索引总是返回“Teste”
  • 是的,我做了这个改变。当我注册一个新用户时,这一行显示以下错误: var userType = user.UserType; System.NullReferenceException: Object reference not set to an instance of an object. 我可以登录,但索引上显示“teste” .在调试中,我可以使用 UserName 字段,但不能使用 UserType。
  • 第一条评论见:What is a NullReferenceException and how do I fix it? 第二条评论:当 UserName 有效而 UserType 无效时,数据库中未设置 UserType。

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


【解决方案1】:

请参阅这篇文章以获得很好的解释,When to use ViewBag, ViewData, or TempData

.. 一旦控制器重定向,ViewBag 和 ViewData 将包含空值。如果您在重定向后使用调试工具检查 TempData 对象,您会看到它已完全填充。

改为这样做:

TempData["UserType"] = userType;

相应地改变你的观点,即

@{var tempUserType = TempData["UserType"]} // in the top

然后像使用 ViewBag 一样使用它

【讨论】:

  • 嗨@Twice 你能看一下问题cmets上显示的问题吗?谢谢
  • @PedroHenrique 您如何访问视图中的 TempData?
  • 是的,我试过了,这里是我的观点:@if (Request.IsAuthenticated &amp;&amp; TempData["UserType"]=="Musico") { &lt;span&gt;musico&lt;/span&gt; } else if (Request.IsAuthenticated &amp;&amp; TempData["UserType"] == "Ouvinte") { &lt;span&gt;ouvinte&lt;/span&gt; } else{ &lt;span&gt;teste&lt;/span&gt; }
  • @PedroHenrique 尝试TempData["UserType"] = "User type 123"; 然后在重定向操作中您可以ViewBag.UserType = TempData["UserType"]; 并在您看来@if (TempData["UserType"] == "User type 123"){//do something}。这应该有效。在您的情况下,我怀疑这是因为您的 userType 为空,这就是它不起作用的原因。调试一下看看是不是这样。
  • 在我的调试中,我发现问题出在登录方法中的 var currentUser 上,它没有被用户占用。我发了另一个帖子来问这个问题,你能看一下吗? stackoverflow.com/questions/26328660/…谢谢
【解决方案2】:

ViewBag 由于重定向而丢失。 一个简单的解决方案是使用TempData,它只在一个额外的请求后仍然有效。之后,它通常会消失,但是有一个 Keep 方法。

来自 MSDN:

但是,TempDataDictionary 对象中的数据仅从 一个请求到下一个请求,除非您标记一个或多个键 使用 Keep 方法保留。如果密钥被标记为保留, 为下一个请求保留密钥。

例子:

[Authorize]
public class AccountController : Controller
{
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // do stuff
            TempData["UserType"] = userType;
            return RedirectToAction("Index", "Home");
        }
        // something went wrong, return view
        return View(model);
    }
}

[Authorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.UserType = TempData["UserType"];
        return View();
    }
}

【讨论】:

  • 感谢@Silvermind,我更新了我的代码以使用 TempData,但是,当我运行应用程序时,索引显示 viewbag 有一个空值 :( 我需要在视图中更新一些东西?
  • 您能否将您的更改添加到您的问题中?
  • 完成! @Silvermind登录/注册后显示的异常是“异常:无法对空引用执行运行时绑定”
猜你喜欢
  • 1970-01-01
  • 2015-02-07
  • 2015-11-12
  • 1970-01-01
  • 2015-02-26
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多