Home > OS >  C# and ASP.NET MVC : how to check if record exist in database and return id
C# and ASP.NET MVC : how to check if record exist in database and return id

Time:01-10

I'm creating an ASP.NET MVC application in C# to collect users into a database.

The initial page will be a form to search if the client already exist in database.

If it does not exist, I will redirect to a subscription page; if it already exists, I need to redirect to detail page to show the information.

The main problem that I have is when I find the client an try to show the detail, I cant get the id associated with the client above an example:

In the database I have:

EmpID Name Address Age Salary Worktype
0 Kevin Boston 23 1000 Dev

I need to match the EmpID == 0 with the Name == Kevin.

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult IndexDetail([Bind(Include = "EmpID,Name")] EmployeeDetails employeeDetails)
{
    if (ModelState.IsValid)
    {
        var userexist = db.EmployeeDetails.Any(x => x.Name == employeeDetails.Name);

        if (userexist)
        {
            return RedirectToAction("Details", "Register", new { id = employeeDetails.EmpID });
        }
        else
        {                   
            return RedirectToAction("Create", "Register", new { id = employeeDetails.EmpID });
        }
    }

    return View(employeeDetails);
}

public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    EmployeeDetails employeeDetails = db.EmployeeDetails.Find(id);

    if (employeeDetails == null)
    {
        return HttpNotFound();
    }

    return View(employeeDetails);
}

If someone can help me in this matter, I am very grateful.

CodePudding user response:

Your error is when referencing the ID of the existing record here:

var userexist = db.EmployeeDetails.Any(x => x.Name == employeeDetails.Name);

if (userexist)
{
    return RedirectToAction("Details", "Register", new { id = employeeDetails.EmpID });
}
else
{                   
    return RedirectToAction("Create", "Register", new { id = employeeDetails.EmpID });
}

Referencing employeeDetails.EmpID in this part is faulty, because the ID doesn't exist on your form, or more precise, it reverts do default value. You should get the ID of the record that is already saved in the database:

if (userexist)
{
    var emId = db.EmployeeDetails.FirstOrDefault(x => x.Name == employeeDetails.Name).EmpID;
    return RedirectToAction("Details", "Register", new { id = emID });
}
  •  Tags:  
  • Related