[英]Remote Validation of Uniqueness in ASP MVC
使用ASP MVC和SQL Server,我試圖在通過其電子郵件值的唯一性創建客戶端之前測試客戶端的存在。
經過大量的教程和解決方案,我未能成功解決此問題。 這是我嘗試過的:
ClientController:
[HttpPost]
public ActionResult Create(Client cmodel)
{
try
{
if (ModelState.IsValid)
{
ClientManagement cdb = new ClientManagement();
if (cdb.AddClient(cmodel))
{
ViewBag.Message = "Client Details Added Successfully";
ModelState.Clear();
}
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public JsonResult IsClientExist(string Email)
{
List<Client> cm = new List<Client>();
return Json(!cm.Any(x => x.Email == Email), JsonRequestBehavior.AllowGet);
}
客戶管理類:
public bool AddClient(Client cmodel)
{
connection();
SqlCommand cmd = new SqlCommand("AddNewClients", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Email", cmodel.Email);
cmd.Parameters.AddWithValue("@Password", cmodel.Password);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i >= 1)
return true;
else
return false;
}
模特客戶:
public class Client
{
[Display(Name = "Email")]
[Required(ErrorMessage = "Email is required.")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
[DataType(DataType.EmailAddress)]
[StringLength(30)]
[Remote("IsClientExist", "Client", ErrorMessage = "Email is already exists in Database.")]
public string Email { get; set; }
[Display(Name = "Password")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "Password is required.")]
public string Password { get; set; }
}
查看創建:
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
您需要在數據庫中的電子郵件上添加唯一約束或唯一索引。
即使在插入之前檢查是否存在,並發請求也可能導致重復。 因此,讓數據庫強制唯一性並處理嘗試插入重復項時返回的錯誤。
您當前的代碼再次檢查Client
的空列表。 您應該檢查現有數據。
您可以編寫一種方法來檢查
private bool DoesEmailExist(string email)
{
var conStr = @"putYourConnectionStringHere";
var q = "select TOP 1 Email from Client WHERE Email=@email";
using (var c =new SqlConnection(conStr))
{
using (var cmd = new SqlCommand(q, c))
{
c.Open();
cmd.Parameters.AddWithValue("@email", email);
var r = cmd.ExecuteReader();
return r.HasRows;
}
}
}
現在,您可以在其他方法中調用此方法。 當電子郵件存在於系統中時, IsClientExist
應該返回false
,而在數據庫中不存在時應返回true
。 因此,基本上,您需要否定來自DoesEmailExist
方法返回的結果
public JsonResult IsClientExist(string Email)
{
var r = DoesEmailExist(Email);
return Json(!r, JsonRequestBehavior.AllowGet);
}
請記住,這僅進行客戶端驗證。 永遠不要信任來自客戶端的數據。始終在服務器端進行驗證 。 您應該添加數據庫級別約束,以防止重復的電子郵件被保存在表中,就像@David Browne在他的回答中提到的那樣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.