In product class i have code properties which need to be unique. I use remote validation. but it makes problem when editing. so i add AdditionalFields. it works fine when perform edit operation but product can not create now. it never hit controller when use AdditionalFields in remote validation.. My model:
public class Product
{
public int Id { get; set; }
[Remote("IsCodeAvailable", "Product", AdditionalFields ="Id", HttpMethod = "GET", ErrorMessage = "Product Code already taken")]
public string Code { get; set; }
public string Name { get; set; }
}
here is my validation code
[HttpGet]
public JsonResult IsCodeAvailable(string code, int Id)
{
try
{
var flag = true;
if (Id == 0) // its a new object
{
flag = !db.Product.Any(x => x.Code == code);
}
else // its an existing object so exclude existing objects with the id
{
flag = !db.Product.Any(x => x.Code == code && x.Id != Id);
}
return Json(flag, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
and here is my view
<div class="form-horizontal">
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Code, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Code, new { htmlAttributes = new { @class = "form-control", @required = "required", @style = "text-transform:uppercase" } })
@Html.ValidationMessageFor(model => model.Code, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
Any kind of help will be greatly appreciated