【问题标题】:issue with form C# asp.net mvc表单 C# asp.net mvc 的问题
【发布时间】:2014-06-25 15:14:44
【问题描述】:

我正在用 asp.net 4.0 C# 开发一个网站。我使用 mvc 4.0 我必须实现一个表单,但是当我提交它时。我想执行某种方法,但我不知道如何。

浏览量: <FORM action="...?..." method="post"> <div class="identification"> id @Html.TextBox("id") password @Html.Password("password") </div> <input type="submit" value="login" /> </FORM>

控制器(名为 loginControllers.cs)

public partial class login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
protected Boolean Login_Click(object sender, EventArgs e)
{
    string p = "LDAP://wrexham.ac.uk";
    // string p = "LDAP://wxmdc1.wrexham.local";
    string u = id.text;
    string pw = password.Text;

    if (AuthenticateUser(p, u, pw))
    {
        FormsAuthentication.SetAuthCookie(u, false);
        //FormsAuthentication.Authenticate()
        //FormsAuthentication.RedirectFromLoginPage(txtUser.Text, chkPersistLogin.Checked)
        //FormsAuthentication.RedirectFromLoginPage(u, false);

        //FormsAuthentication.SetAuthCookie()
        Response.Write("True");
        return true;


    }
    else
    {
        Response.Write("false");
        return false;
    }
}

protected bool AuthenticateUser(string path, string user, string pass)
{
    //Simple Active Directory Authentication Using LDAP and ASP.NET
    DirectoryEntry de = new DirectoryEntry(path, user, pass, AuthenticationTypes.Secure);
    try
    {
        //run a search using those credentials.
        //If it returns anything, then you're authenticated
        DirectorySearcher ds = new DirectorySearcher(de);
        ds.FindOne();
        return true;
    }
    catch (Exception ex)
    {
        //otherwise, it will crash out so return false
        Response.Write(ex.Message);
        return false;
    }
}
protected void btnCancel_Click(object sender, EventArgs e)
{

}

}

【问题讨论】:

  • 您提供的代码绝对不是用于 MVC 控制器的。

标签: c# asp.net-mvc


【解决方案1】:

你应该像这样创建你的视图:

@model Yournamespace.Models.ModelName


<div>
        @using (Html.BeginForm("MethodName", "ControllerName", FormMethod.Post, new { @class = "css class if any" }))
        {             
            <section>
                <div class="input-block">
                    <strong><label>yOur Label</label></strong>
                    @Html.EditorFor(model => Model.Attribute)
                    <div class="UserIdValidation">
                        @Html.ValidationMessageFor(model => Model.Attribute)
                    </div>
                </div>

                <p style="margin-top: 25px" class="input-block">
                    <input type="submit" value="Submit">
                </p>              
            </section> 
        }
</div>

你的控制器动作应该是这样的:

 public class ControllerNameController : Controller
 {
        [HttpPost]
        public ActionResult Login(ModelName model)
        {           

              return View("VewName");
        }
 }

【讨论】:

    【解决方案2】:

    您需要创建一个LoginViewModel,它是处理用户登录详细信息和创建 MVC 视图所必需的。例如:

    ** 未经测试的代码!! **

    public class LoginViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }
    
        [Required]
        [Display(Name = "Password")]
        public string Password { get; set; }
    
        [Display(Name = "Remember on this computer")]
        public bool RememberMe { get; set; }
    
        /// <summary>
        /// Checks if user with given password exists in LDAP
        /// </summary>
        /// <param name="_username">User name</param>
        /// <param name="_password">User password</param>
        /// <returns>True if user exist and password is correct</returns>
        public bool IsValid(string _username, string _password)
        {
    
            //Simple Active Directory Authentication Using LDAP and ASP.NET
            var _path = "LDAP://a.b.c/dc=a,dc=b,dc=c";
            DirectoryEntry de = new DirectoryEntry(_path, _username, _password, AuthenticationTypes.Secure);
            try
            {
               //run a search using those credentials.
               //If it returns anything, then you're authenticated
               DirectorySearcher ds = new DirectorySearcher(de);
               SearchResult result = ds.FindOne();
               if (null == result)
               {
                  return false;
               }               
               return true;
            }
            catch (Exception ex)
            {
               //otherwise, it will crash out so return false
               return false;
            }
        }
    }
    

    LoginController 的逻辑:

    public class LoginController : Controller
    {
        //
        // GET: /Login/
        public ActionResult Index()
        {
            return View();
        }
    
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
    
        [HttpPost]
        public ActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.IsValid(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Login data is incorrect!");
                }
            }
            return View(model);
        }
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
    

    您的登录视图:

    @model Models.LoginViewModel
    @{
        ViewBag.Title = "Login";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    @using (Html.BeginForm("Login", "Login", FormMethod.Post))
    {
        @Html.ValidationSummary(true, "Login failed. Check your login details.");
        <div>
            <fieldset>
                <legend>Login</legend>
                <div class="editor-label">
                    @Html.LabelFor(m => m.UserName)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.UserName)
                    @Html.ValidationMessageFor(m => m.UserName)
                </div>
                <div class="editor-label">
                    @Html.LabelFor(m => m.Password)
                </div>
                <div class="editor-field">
                    @Html.PasswordFor(m => m.Password)
                    @Html.ValidationMessageFor(m => m.Password)
                </div>
                <div class="editor-label">
                    @Html.CheckBoxFor(m => m.RememberMe)
                    @Html.LabelFor(m => m.RememberMe)
                </div>
                <input type="submit" value="Log In" />
            </fieldset>
        </div>
    }
    

    您的 _Layout.cshtml 代码应如下所示:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
        <title>@ViewBag.Title</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div style="width: auto; background-color: #728ea7;">
            @if (Request.IsAuthenticated) {
                <strong>@Html.Encode(User.Identity.Name)</strong>
                @Html.ActionLink("Sign Out", "Logout", "Login")
            }
            else {
                @Html.ActionLink("Register", "Register", "Login")
                <span> | </span>
                @Html.ActionLink("Sign In", "Login", "Login")
            }
        </div>
    
        @RenderBody()
    
        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多