且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在MVC中的控制器操作方法中进行自定义验证

更新时间:2021-11-04 00:36:01

我看到你的代码的方式,我会在重新运行应用程序之前做一些更改,

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.