我正在使用c#在mvc4中进行我的web项目。现在我正在创建一个登录页面。我使用过以下代码。用户名和密码在sql数据库表中
@using (Html.BeginForm())
{
@Html.LabelFor(model => model.Mem_Email)
@Html.EditorFor(model => model.Mem_Email)
@Html.ValidationMessageFor(model => model.Mem_Email)
@Html.LabelFor(model => model.Mem_PWD)
@Html.EditorFor(model => model.Mem_PWD)
@Html.ValidationMessageFor(model => model.Mem_PWD)
<input type="submit" value="Log In" />
}
public ViewResult Login()
{
return View();
}
[HttpPost]
public RedirectResult Login(FormCollection form)
{
string uid = Request.Form["Log_email"];
string pwd = Request.Form["Log_pwd"];
bool IsUser=new Member().GetLogin(uid,pwd);
if (IsUser == true)
{
System.Web.Security.FormsAuthentication.SetAuthCookie(uid, true);
return Redirect("~/Member/MemberHome");
}
else
return Redirect("~/Member/Login");
}
public bool GetLogin(string email,string pwd)
{
bool IsUser = false;
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(
"SELECT COUNT (*) FROM Mem_Register WHERE Mem_Email='" +
email + "' AND Mem_PWD='" + pwd + "'", con))
{
con.Open();
int count = (int)cmd.ExecuteScalar();
if (count == 1)
{ IsUser = true; }
}
}
return IsUser;
}
这不起作用。表单中的内容不会传递给控制器。我不知道这是登录用户的正确方法。请帮帮我。
答案 0 :(得分:2)
首先,您不应该使用FormCollection。由于您使用的是强类型模型,因此您应该将该模型发布到您的操作中。
其次,您在视图中使用了名称Mem_Email
和Mem_PWD
,但您正在寻找Log_email
和Log_pwd
的FormCollection值,您不会找到。
答案 1 :(得分:0)
在视图中使用此代码
@using (Html.BeginForm())
{
<div>
<fieldset>
<legend>Login</legend>
@Html.LabelFor(u => u.Email)
@Html.TextBoxFor(u => u.Email)
@Html.ValidationMessageFor(u => u.UserName)
@Html.LabelFor(u => u.Password)
@Html.PasswordFor(u => u.Password)
@Html.ValidationMessageFor(u => u.Password)
<input type="submit" value="Log In" />
</fieldset>
</div>
}
答案 2 :(得分:0)
@Erik给出的解决方案是正确的,您在控制器中使用不同的命名约定。您必须使用与视图中相同的Form值
[HttpPost]
public RedirectResult Login(FormCollection form)
{
string uid = Request.Form["Mem_Email"];
string pwd = Request.Form["Mem_Email"];
bool IsUser=new Member().GetLogin(uid,pwd);
if (IsUser == true)
{
System.Web.Security.FormsAuthentication.SetAuthCookie(uid, true);
return Redirect("~/Member/MemberHome");
}
else
return Redirect("~/Member/Login");
}
使用较早的一个,即Log_email
和Log_pwd
,您将在控制器中获得空值。