Reputation: 29
I am creating an MVC application. I am getting a null value in variable when I fetching data from database.
Here is my change password view code
@using (Html.BeginForm("Changepassword", "Home", FormMethod.Post))
{
<table class="center">
<tr>
<td>Old Password</td>
<td>
@Html.EditorFor(pass => pass.Password)
</td>
<td>@Html.ValidationMessageFor(pass => pass.Password)</td>
</tr>
<tr class="rowspace">
<td>New Password</td>
<td>
@Html.EditorFor(pass => pass.NewPassword)
</td>
<td>@Html.ValidationMessageFor(pass => pass.NewPassword)</td>
</tr>
<tr class="rowspace">
<td colspan="3" id="button">
<input type="submit" value="Change Password" /></td>
</tr>
<tr class="rowspace"><td colspan="3">@ViewBag.Message</td></tr>
</table>
}
Here is my Home controller code.
Problem I am facing - var userDetail is returning null and when i checked and debug my code using breakpoint my login.Email is not fetching email from database and it is returning null.
public ActionResult Changepassword(tblUser login)
{
using (UserDetailsEntities db = new UserDetailsEntities())
{
var detail = db.tblUsers.Where(log => log.Password == login.Password).FirstOrDefault();
if (detail != null)
{
var userDetail = db.tblUsers.FirstOrDefault(c => c.Email == login.Email);
if (userDetail != null)
{
userDetail.Password = login.NewPassword;
db.SaveChanges();
ViewBag.Message = "Record Inserted Successfully!";
}
else
{
ViewBag.Message = "Password not Updated!";
}
}
}
return View(login);
}
Upvotes: 0
Views: 3790
Reputation: 7766
In your view email for the model is not assigning so it will be always null when its get posted. Best practice is to ask for the email also at the time of password change. Check code below Your view
@using (Html.BeginForm("Changepassword", "Home", FormMethod.Post))
{
<table class="center">
<tr>
<td>Email</td>
<td>
@Html.EditorFor(pass => pass.email)
</td>
<td>@Html.ValidationMessageFor(pass => pass.email)</td>
</tr>
<tr>
<td>Old Password</td>
<td>
@Html.EditorFor(pass => pass.Password)
</td>
<td>@Html.ValidationMessageFor(pass => pass.Password)</td>
</tr>
<tr class="rowspace">
<td>New Password</td>
<td>
@Html.EditorFor(pass => pass.NewPassword)
</td>
<td>@Html.ValidationMessageFor(pass => pass.NewPassword)</td>
</tr>
<tr class="rowspace">
<td colspan="3" id="button">
<input type="submit" value="Change Password" /></td>
</tr>
<tr class="rowspace"><td colspan="3">@ViewBag.Message</td></tr>
</table>
}
Controller
public ActionResult Changepassword(tblUser login)
{
using (UserDetailsEntities db = new UserDetailsEntities())
{
var detail = db.tblUsers.Where(log => log.Password == login.Password
&& log.email == login.email).FirstOrDefault();
if (detail != null)
{
userDetail.Password = login.NewPassword;
db.SaveChanges();
ViewBag.Message = "Record Inserted Successfully!";
}
else
{
ViewBag.Message = "Password not Updated!";
}
}
return View(login);
}
Upvotes: 1