在 MVC 中的两个视图请求之间保留信息

本文关键字:视图 两个 请求 之间 信息 保留 MVC | 更新日期: 2023-09-27 18:34:35

我基本上有两种观点。第一个视图将用户名作为输入并生成密码并重定向到第二个视图。当用户在第一个视图中输入控件并将该模型传递给第二个视图时,我将用户输入存储在模型中。如何在第二个视图中检索该值。请在下面找到我的代码,如果我犯了什么错误,请告诉我。

public ActionResult GetOTP(string Login) 
{ 
    // string user = model.Login; 
    if (!System.String.IsNullOrEmpty(Login)) 
    { 
        int otpass; 
        bool conversion = Int32.TryParse(Encryption.GetPassword(Login), out otpass); 
        if (conversion) 
        { 
            //Save user credentials. 
            User userModel = new User(); 
            userModel.Login = Login; 
            userModel.Otp = otpass; 
            string otp1 = otpass.ToString(); 
            userModel.OtpCrtDate = DateTime.Now; 
            ViewBag.user = userModel.Login; 
            ViewBag.date = userModel.OtpCrtDate; 
            ViewBag.password = Convert.ToString(otpass); 
            ViewBag.status = "OTP: " + otpass + " remains active just 30 seconds from now."; 
            return View("Access",userModel); 
            // return View("GetOTP", userModel); 
        } 
        else 
        { 
            ViewData["status"] = "Sorry, an error was found while creating your password. Try again, please."; 
            return View("GetOtp"); 
        } 
    } 
    else
        return View("GetOtp"); 
    } 
}
public ActionResult Access(User model,string Login, int otp) 
{ 
    if (otp == model.Otp && Login == model.Login) 
    { 
        TimeSpan timeSub = DateTime.Now - model.OtpCrtDate; 
        if (timeSub.TotalSeconds < 30.0) 
        { 
            //LogIn successful 
            //Model.Logged = true; 
            return View("../PrivateArea/Account"); 
        } 
        else 
        { 
            ViewData["status"] = "Sorry but your OTP is very old. Get a new one."; 
            return View("UserGetOtp"); 
        } 
    } 
    return View("Access"); 
}

在 MVC 中的两个视图请求之间保留信息

您可以使用

SessionTempData在两个请求之间持久化数据,如以下简单示例所示:会期:

public ActionResult SampleBook5()
{
    Book book = new Book
    {
        ID = 1,
        BookName = "Sample Book",
        Author = "Sample Author",
        ISBN = "Not available"
    };
    Session["BookData"] = book;
    return RedirectToAction("SampleBook6");
}
public ActionResult SampleBook6()
{
    Book book = Session["BookData"] as Book;
    return View(book);
}

温度数据:

public ActionResult SampleBook3()
{
    Book book = new Book
    {
        ID = 1,
        BookName = "Sample Book",
        Author = "Sample Author",
        ISBN = "Not available"
    };
    TempData["BookData"] = book;
    return RedirectToAction("SampleBook4");
}
public ActionResult SampleBook4()
{
    Book book = TempData["BookData"] as Book;
    return View(book);
}

使用 SessionTempData 之间的主要区别在于,我们可以使用会话变量来持久保存完整用户会话的数据 另一方面,我们使用TempData将一些数据从一个操作方法传递到另一个操作方法