Donate

Restrict Remote Validation In ASP.NET MVC Edit Mode.

Hello,

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)
Model: Add AdditionalFields in Remote Attribute.
[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;
 }
}
Controller: Return true if InitProductCode is equal to ProductCode.
[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

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input