Hi @Ahmed Mulu ,
How can I restrict the Remote attribute to behave in Edit mode?
You can try to use the following methods:
- Use two view models. In the Create page, use the CreateDCO model with remote attribute. On the Edit page, use the EditDCO model without the remote attribute. [Note] Using this method, when doing CRUD operations, you need to convert the model between DCO model (assume this model is used to map the database entity) and the CreateDCO/EditDCO model.
- Use the Additional fields with Remote attribute.
For example, you can use the following model, add a PageMode property to set the page mode (Create or Edit)
public class DCOViewModel
{
[Required]
[StringLength(255)]
[Remote("recordexist", "Home",AdditionalFields = nameof(PageMode) , ErrorMessage = "Error! ID Already Exists")]
public string DCOID { get; set; }
public string PageMode { get; set; } //use this property to set the page mode: Create, Edit mode
[Required]
[StringLength(255)]
public string FullName { get; set; }
[Required]
[StringLength(6)]
public string Sex { get; set; }
[StringLength(255)]
public string AcadamicBackground { get; set; }
}
Then, in the controller, in the Get action method (Create and Edit), set the PageMode property.
public IActionResult CreateDCO()
{
var newitem = new DCOViewModel() { PageMode = "Create" }; //set page mode
return View(newitem);
}
[HttpPost]
public IActionResult CreateDCO(DCOViewModel viewmodel)
{
if (ModelState.IsValid)
{
}
return View();
}
public IActionResult EditDCO(string DCOID)
{
List<DCOViewModel> items = //get DCO from database
var item = items.First(d => d.DCOID == DCOID);
item.PageMode = "Edit"; //set page mode
return View(item);
}
[HttpPost]
public IActionResult EditDCO(DCOViewModel viewmodel)
{
if (ModelState.IsValid)
{
}
return View();
}
public JsonResult recordexist(string DCOID, string pageMode)
{
List<DCOViewModel> items = //get dco from database
//based on the page model to check whether the data is exist or not
if(pageMode == "Create")
{
return Json(!items.Any(d => d.DCOID == DCOID));
}
return Json(true);
}
And in the view page, use a hidden field to store the PageMode.
<div class="form-group">
<label asp-for="DCOID" class="control-label"></label>
<input asp-for="DCOID" class="form-control" />
<input asp-for="PageMode" class="form-control" type="hidden" />
<span asp-validation-for="DCOID" class="text-danger"></span>
</div>
The result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion