Click here to Skip to main content
15,905,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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);
        }


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.
Posted
Updated 23-Apr-17 2:12am

1 solution

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");
    }

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,
C#
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.
 
Share this answer
 
Comments
ammu11 23-Apr-17 9:25am    
This answer is perfect and I solved my problem Thank you so much. Can I ask you 1 more doubt if I want to check only the first four letter of the new name that was given, with the matching first four letter in the db ??if the letter matches error message is shown else data is added to the table how can it be possible ??
Afzaal Ahmad Zeeshan 23-Apr-17 9:46am    
That is possible, and that is exactly the same issue here. You send the name as 4 character word, and then get the result as either existing, or available.

However, since that approach is similar to this one, there is no need to intentionally approach for that. Just let the user enter the desired username, and see if that is available after he is done entering value.

Also, for that approach, you would require to use AJAX and send request with those 4-5 characters, each time he enters something.

As this post has solved your problem, would you mind formally accepting as a solution, there is also a rating bar that you can select to rate my answer. Thank you. :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900