在MVC 5中的不同操作中使用文本框值

本文关键字:文本 操作 MVC | 更新日期: 2023-09-27 18:26:38

我在Login视图中有这些输入,我想在代码的不同部分使用它们的值,我使用Request.Form["]。但这只适用于此视图的操作(登录操作)。是否有任何方法可以在许多操作中使用该值?

@using (Html.BeginForm("ConfirmRegistration", "Regestration"))
    {
<h4>userName: <input type = "text" name="USERNAME" class="form-control" id="USERNAME"  /></h4>
<h4>Password: <input type = "password" name="pasword" class="form-control" id="pasword" /></h4>
<input type="submit" value="Login" class="btn-primary" />
   }

在MVC 5中的不同操作中使用文本框值

您可以在C#代码中使用Session。您的控制器操作方法将类似于此。

        public ActionResult Login(FormCollection form)
        {
            //first, your logic to log user in
            //if credentials match, then store them into the Session
            Session["username"] = form["USERNAME"].ToString();
            Session["password"] = form["pasword"].ToString();

        }
        //to access the data from some other action, write:
        public ActionResult anyAction()
        {
            string username = Session["username"].ToString();
            string password = Session["password"].ToString();
            //and then do whatever you wanna do with them
        }

它们甚至可以在您的视图级别访问。只需使用像@Session["username"].toString()@Session["password"].toString()这样的C#剃须刀来获得值。