[英]Display error message if ID not Found in mvc4
My employee(Customer) diary is based on CustomerID, see this image . 我的员工(客户)日记基于CustomerID, 请参见此图像 。
If I am creating new Diary I need the CustomerID. 如果要创建新日记,则需要客户ID。
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. 如果我使用的数据库中存在正确的CustomerId,则它可以正常工作,但是如果我使用的CustomerID不正确,则它向我显示视图并显示有关其他字段的错误。
I just want to see the error message saying "ID not found" 我只想查看错误消息“找不到ID”
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 这是我的创建日记代码和图像@nd图片,如果我输入错误的customerID我的创建日记的控制器代码,我只想看到一条错误消息
// POST: /Diary/Create // 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: 首先根据输入的CustomerId
添加要检查的条件,并根据需要添加模型错误:
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) 然后将以下内容添加到您的视图(或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. 我建议显示由用户选择的客户列表,这将改善UI体验并避免出现此类错误。
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.