使用Html.BeginForm来提交表单

以用户登录这个功能作为例子。
View中主要使用了Html.BeginForm(),
它在客户端产生一个
标签。
具体代码如下:
            <% using (Html.BeginForm()){ %>
           

                   

  •                    
    电子邮件:

                       

                   

  •                

  •                    
    密     码:

                       

                   

  •            

           

            <% } %>
除去<%%>中的内容,其他的html标签跟原始的html文件没什么两样,根本不使用传统的asp.net服务器端控件。
Controller中的login action 对应了相应的View.
要完成用户登录这个功能,首先要用Get的方法获取一个View,然后要用Post的方法接受提交的表单进行用户登录验证处理。
所以在Controller中会有两个Login action 但是这两个是不一样的,区别就在于GET和POST。
Get action 比较简单,如下:
        //
        // GET: /Account/Login/
        public ActionResult Login()
        {
            return View();
        }
POST action 比较复杂一些,要从Model模型中调用相应的功能,如下:

//
        // POST: /Account/Login

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(FormCollection collection)
        {
            try
            {
                string email = collection["email"];
                string password = collection["password"];
                password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "md5");

                XuShop.Models.common.membersInfo mi = new XuShop.Models.bll.members().Login(email, password);
                if (mi != null)
                {
                    HttpCookie c = new HttpCookie("member");
                    c.Value = XuShop.Models.web.Util.Member2String(mi);
                    c.Expires = DateTime.Now.AddDays(7);
                    Response.Cookies.Add(c);
                    System.Web.Security.FormsAuthentication.SetAuthCookie(mi.Email, false);

                    string url = Request.QueryString["ReturnUrl"];
                    if (!string.IsNullOrEmpty(url))
                        Response.Redirect(url);
                    return RedirectToAction("Index","Home");
                }
                else
                {
                    ViewData["msg"] = "帐户或密码错误!";
                    return View();
                }
            }
            catch(System.Exception ex)
            {
                ViewData["msg"] = ex.Message;
                return View();
            }
        }

上面的 [AcceptVerbs(HttpVerbs.Post)]
指示该action使用POST。默认使用的是GET.


转载于:https://www.cnblogs.com/xushop/articles/1561428.html

你可能感兴趣的:(使用Html.BeginForm来提交表单)