Restrict Remote Validation In ASP.NET MVC Edit Mode.
Hello,
Model: Add AdditionalFields in Remote Attribute.
Controller: Return true if InitProductCode is equal to ProductCode.
In data entry operations, we normally validate user input if they exist in the database, if yes we throw some kind of exception or error message that the data they entered already exists in the database. But in scenario like editing of existing information, we don't want this to happen. So to restrict the remote validation in ASP.NET MVC, I found the fix from stack Remote validation restrict for edit controller method but modified the logic in the controller which is to return a JSON rather than a bool value. The code modifications are as follows.
Edit View or Edit Partial View: Add another HiddenField for Initial Product Code used for Comparison.
@Html.Hidden("InitProductCode", Model.ProductCode)
[Display(Name = "Product Code")] [Required(ErrorMessage = "ProductCode is required")] [Remote("CheckProductCode", "Products", HttpMethod = "POST", ErrorMessage = "Existing ProductCode Entered.", AdditionalFields = "InitProductCode")] public int ProductCode { get { return _productCode; } set { _productCode = value; } }
[HttpPost] public JsonResult CheckProductCode(int ProductCode, string InitProductCode) { bool found; found = false; clsProductEntryDBQuery dataEntryQuery = new clsProductEntryDBQuery(); if (InitProductCode != "undefined") { if (ProductCode == Convert.ToInt32(InitProductCode)) return Json(true, JsonRequestBehavior.AllowGet); } dataEntryQuery.ValidateProductCode(ProductCode, ref found); return Json(found, JsonRequestBehavior.AllowGet); }
Comments
Post a Comment