首页 > 解决方案 > Can viewbag handle redirects while still maintaining its value?

问题描述

i'm just wondering how to maintain it for some conditional if statements on the index page. on my index page i have a conditonal if statement set which will show the loginform if admin user is null, once submit is pressed this conditional if statement should no longer be loading the form instead the homepage and navbar should show.

     @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();}

here is my view for the action

      [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);
     }

The results i was currently expecting is that when viewbag.users != null then the form shouldn't show up at all

Summary: Once i press submit on the form it goes to the ValidateUser action to validate whether that person is admin or not. Then it saves the person details in Viewbag.Users. Hence viewbag.Users is not empty anymore therefore that if statement shouldn't be working anymore but it is still showing the login form

Answer: viewbag doesn't presist between requests therefore use viewtemp or cookies or a query

标签: c#htmlmodel-view-controllerview

解决方案


你原来的问题的答案是:

不,您的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 在重定向操作的两个控制器之间保持信息。


推荐阅读