我正在控制器部件操作方法中进行验证,并且我遇到了一个问题,即通过检查名称不应该出现在表中的条件来验证名称。我尝试了很多条件,但总是遇到一些错误。任何人都可以帮我找到我的问题的解决方案??? 控制器
I am doing validation in controller part action method and I got stuck at a point that to give validation for name by checking the condition that the name should not appear already in the table. I have tried many conditions but always getting some error. can anyone please help me to find solution for my problem ??? controller
[HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create([Bind(Include = "Id,Name")] Student student) { TempData["name"] = student.Name; var show = db.Students.Select(e => e.Name).ToList(); if (show == TempData["name"]) { ModelState.AddModelError("Name", "Name already exists"); } if (ModelState.IsValid) { db.Students.Add(student); await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(student); }这是我的控制器进行检查,我正在从var show中的表中检索所有名称,然后我需要检查show中的结果是否存在,如果新名称不在show中,我需要将其输入表中,否则需要将错误消息显示为ModeState.AddModelError()。任何人都可以帮我找到解决问题的方法??? 我尝试了什么: 已经通过多种方式进行了检查,但总是会收到新名称已经存在的错误。
This is my controller for checking , I am retrieving all the names from table in var show , then I need to check whether the result in show is there or not and if the new name is not in show I need to enter it into the table else need to show the error message as ModeState.AddModelError(). Can anyone please help me to find a solution for my problem ??? What I have tried: had checked in many ways but always getting error that the new name given is already exist.
推荐答案我看到你的代码的方式,我会在重新运行应用程序之前做一些更改, The way I see your code, I would make a few changes before even rerunning the application, public async Task<ActionResult> Create([Bind(Include = "Id,Name")] Student student) { // No need for a temp variable, I can get the Name from parameter. var show = db.Students.Select(e => e.Name).ToList(); // "show" is a List<T> variable; List<string> // Thus, check if the list contains this name if (show.Contains(student.Name)) { ModelState.AddModelError("Name", "Name already exists"); }
这是一种正确的方法,为什么?因为,之前您尝试针对临时变量检查列表,该临时变量通常会返回 object 类型数据。我不确定为什么这个决定为真。 这种行为有另一种方法,
This would be a proper way to do this, why? Because, previously you were trying to check a list against a temporary variable which would typically return object type data. I am unsure as to why that resolved to true. There is another approach to this kind of behavior,
var show = db.Students.Where(e => e.Name == student.Name).ToList(); if(show != null && show.Count != 0) { // There exists a user } else { // Add the user }也许,这种方法可以解决您的问题。
Perhaps, this approach would solve your problem here.
更多推荐
在MVC中的控制器操作方法中进行自定义验证
发布评论