【问题标题】:Can viewbag handle redirects while still maintaining its value?viewbag 可以在保持其价值的同时处理重定向吗?
【发布时间】:2019-12-25 14:43:14
【问题描述】:

我只是想知道如何为索引页面上的某些条件 if 语句维护它。在我的索引页面上,我有一个条件 if 语句集,如果管理员用户为空,它将显示登录表单,一旦按下提交,此条件 if 语句不应再加载表单,而是应显示主页和导航栏。

     @if (ViewBag.Users == null)
{
         using (Html.BeginForm("ValidateUser", "Home", FormMethod.Post, 
         new { @class = 
                  "form-signin" }))
        {
             ///set text to be centered horizontolly
             <div class="text-center">

        <img class="mb-4" src="~/images/people.svg" alt="" width="72" height="72">
        <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
          @Html.TextBoxFor(m => m.UserEmail, new { @type = "email", id = "inputEmail", Name = "Email Address", @class = "form-control", placeHolder = "Email Address", autocomplete = "off", required = "required" })
           @Html.TextBoxFor(m => m.Password, new { @type = "password", id = "inputPassword", Name = "Password", @class = "form-control", placeHolder = "Password", autocomplete = "off", required = "required" })

        <div class="checkbox mb-3">
            <label>
                <input type="checkbox" value="remember-me"> Remember me
            </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>

           </div>
   }Html.EndForm();}

这是我对行动的看法

      [HttpPost][ActionName("ValidateUser")]
     public IActionResult ValidateUser(Users user)
         {
        ///check if modelstate is active once it is, retrieve the users 
      and add the new identity if it matches
        if(ModelState.IsValid)
        {
            ///simulating a database call for users
            List<Users> admin = user.GetUsers();

           if(admin.FirstOrDefault().UserEmail == user.UserEmail && 
     admin.FirstOrDefault().Password == user.Password)
            {
                ViewBag.Users = user;

                return RedirectToAction("Index");
            }
        }

        return View(user);
     }

我目前期望的结果是,当 viewbag.users != null 时,表单根本不应该出现

总结:一旦我在表单上按下提交,它就会进入 ValidateUser 操作以验证该人是否是管理员。然后它将人员详细信息保存在 Viewbag.Users 中。因此 viewbag.Users 不再为空,因此 if 语句不应再工作,但仍显示登录表单

答案:viewbag 不存在于请求之间,因此使用 viewtemp 或 cookie 或查询

【问题讨论】:

  • 一旦我在表单上按下提交,它就会进入 ValidateUser 操作以验证该人是否是管理员。然后它将人员详细信息保存在 Viewbag.Users 中。因此 viewbag.Users 不再为空,因此 if 语句不应该再工作了,但它仍然显示登录表单
  • 您是否认为ViewBag 在 http 请求之间以某种方式持续存在?如果是这样,答案是否定的——它不会那样做。它仅适用于 单个 http 请求。 RedirectToAction 导致单独的 http 请求。
  • 不,您的 ViewBag 值在重定向期间丢失。您需要使用 TempData 在重定向之间保留您的值。
  • 不是吗?那么你将如何持久化一个对象
  • TempData 将是一种方式(尽管不是我建议的方式)。查询字符串可能是另一个。或者一个 cookie。

标签: c# html model-view-controller view


【解决方案1】:

你原来的问题的答案是:

不,您的 ViewBag 值在重定向期间丢失。您需要使用 TempData 在重定向之间保留您的值。重定向只是一个带有 301、302 或 307 状态代码和 Location 响应标头的空响应。该 Location 标头包含您希望将客户端重定向到的 URL。

但是

您可以使用TempData 将模型数据传递给重定向请求。您可以传递简单类型,如字符串、int、Guid 等。如果您想通过 TempData 传递复杂类型对象,您可以将对象序列化为字符串并传递它。我制作了一个简单的测试应用程序,足以满足您的需求:

您的Controller 看起来像:

public ActionResult TestAction1(ClassA model)
{
    model.Id = "1";
    model.Name = "test";
    model.Marks.Grade = "A";
    model.Marks.Marks = 100;
    var complexObj = JsonConvert.SerializeObject(model);
    TempData["newuser"] = complexObj;
    return RedirectToAction("TestAction2");
}

public ActionResult TestAction2()
{
    if (TempData["newuser"] is string complexObj )
    {
        var getModel= JsonConvert.DeserializeObject<ClassA>(complexObj);
    }
    return View();
}

你的Model 看起来像:

public class ClassA
{
    public ClassA()
    {
        Marks = new StudentMarks();
    }

    public string Id { get; set; }
    public string Name { get; set; }
    public StudentMarks Marks { get; set; }
}

public class StudentMarks
{
    public int Marks { get; set; }
    public string Grade { get; set; }
}

这是一个非常基本的示例,说明如何使用 TempData 在重定向操作的两个控制器之间保持信息。

【讨论】:

    【解决方案2】:

    ViewData 和 ViewBag 用于将数据从控制器传输到视图的相同目的。 通过使用 RedirectToAction("Index") 您正在创建新的 http-Request。 此 ViewBag 或 ViewData 将适用于相同的 http_Request,即返回 View("Index")。

    当您使用 RedirectToAction("Index") 创建新的 http 请求时,您可以使用 TempData。 ( TempData 是存储的数据,就像短时间的实时会话一样。)或 Cookie。

    【讨论】:

      猜你喜欢
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      相关资源
      最近更新 更多