我正在创建一个MVC应用程序。我在更改密码表单功能时出现Null Reference Exception错误。
public partial class tblUser
{
public int Id { get; set; }
[Required(ErrorMessage = "Please Enter Your Email Id")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[Required(ErrorMessage = "Please Enter Your Password")]
[DataType(DataType.Password)]
[StringLength(18, ErrorMessage = "The password must be atleast 3 characters long", MinimumLength = 3)]
public string Password { get; set; }
[Required(ErrorMessage = "Please Enter Your Password")]
[DataType(DataType.Password)]
[StringLength(18, ErrorMessage = "The password must be atleast 3 characters long", MinimumLength = 3)]
public string NewPassword { get; set; }
}
@model MvcWebApplication1.Models.tblUser
<div class="container">
<div class="row rowspace1">
<div class="col-sm-12">
@Html.ActionLink("Log Out", "Login", "Home")
</div>
</div>
<div class="row">
<div id="CpassTitle">
<h3>CHANGE PASSWORD</h3>
</div>
@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>
}
</div>
</div>
当我点击更改密码提交按钮时,我在行NullReferenceException
userDetail.Password = login.NewPassword;
操作方法
[HttpPost]
public ActionResult Changepassword(tblUser login)
{
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);
userDetail.Password = login.NewPassword;
db.SaveChanges();
ViewBag.Message = "Record Inserted Successfully!";
}
else
{
ViewBag.Message = "Password not Updated!";
}
return View(login);
}
答案 0 :(得分:-1)
[HttpPost]
public ActionResult Changepassword(tblUser login)
{
UserDetailsEntities db = new UserDetailsEntities();
var detail = db.tblUsers.Where(log => log.Password == login.Password).FirstOrDefault();
// ADDED NULL CHECK HERE
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);
}
答案 1 :(得分:-1)
检查你的数据库。它在您阅读之前关闭,或者它连接到其他表格。