Reputation: 5293
hi i am doing my web project in mvc4 using c#. Now i am creating a login page. The folowing code i have used.User id and password is in sql database table
@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;
}
This is not working .the content in the form are not passed to controller. i dont know is this the right way to login a user. Please help me.
Upvotes: 0
Views: 807
Reputation: 1289
the solution given by @Erik is right you are using different naming convention in the controller. you must use the same Form value that of in a view
[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");
}
with the earlier one you used ie Log_email
and Log_pwd
you will get null values in the controller.
Upvotes: 0
Reputation: 2523
Use this code in View
@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>
}
Upvotes: 0
Reputation: 93434
First, you shouldn't be using a FormCollection. Since you are using a strongly typed model, you should be posting that model to your action.
Second, you are using the names Mem_Email
and Mem_PWD
in your view, but you are looking for FormCollection values of Log_email
and Log_pwd
, which you wouldn't find.
Upvotes: 2