My employee(Customer) diary is based on CustomerID, see this image .
If I am creating new Diary I need the CustomerID.
If I am using correct CustomerId that is present in database then it works properly, but if I am using an incorrect customerID then its showing the view to me and displaying error about other fields.
I just want to see the error message saying "ID not found"
Here is my create diary Code and image @nd image I just want to see an error message if I am putting in wrong customerID my Controller code for create Diary
// POST: /Diary/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Diary diary)
{
if (ModelState.IsValid)
{
cd.Diaries.Add(diary);
cd.SaveChanges();
return RedirectToAction("Index","Home");
}
return PartialView("_CreateDiary");
}
First add the condition to check based upon the entered CustomerId
and add a model error if needed:
Controller
if (!cd.Customers.Any(c => c.Id == diary.CustomerId)
{
ModelState.AddModelError("CustomerId", "Customer not found");
}
Then add the following to your view (or a ValidationSummary)
View
@Html.ValidationMessage("CustomerId")
I would advise displaying a list of customers that the user selects instead, this will improve the UI experience and also avoid errors like this.
Full controller code
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Diary diary)
{
if (!cd.Customers.Any(c => c.Id == diary.CustomerId)
{
ModelState.AddModelError("CustomerId", "Customer not found");
}
if (ModelState.IsValid)
{
cd.Diaries.Add(diary);
cd.SaveChanges();
return RedirectToAction("Index","Home");
}
return PartialView("_CreateDiary");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.