I have a database with a table called Patient. In my view I have:
<h2>Search by Patient_Name</h2>
@using (@Html.BeginForm("DetailsbyName", "Patient"))
{
@Html.Label("First Name")
@Html.TextBoxFor(model => model.First_Name)
<br />
@Html.Label("Last Name")
@Html.TextBoxFor(model => model.Last_Name)
<input type="submit", value="Submit"/>}
In my controller is the following method:
public ActionResult DetailsbyName(Patient _patient)
{
string Fname = _patient.First_Name;
string Lname = _patient.Last_Name;
try
{
Patient patient = db.Patients.Single(p => p.First_Name == Fname);
patient = db.Patients.Single(p => p.Last_Name == Lname);
return View(patient);
}
catch
{
return RedirectToAction("About", "Home");
}
}
When a user enters a first or last name that occurs more than once in the Database table, the db.Patients.Singlethrows an exception. What might I use other than .Single to handle this?
For instance a user enters First Name: John
Last Name: Smith
If the DB has more than once “John” I currently get an exception. Or if the DB has more than one “Smith” as a last name I get an exception.
Thanks.
Got it working with this:
List<Patient> patientList = db.Patients.Where(p => p.Last_Name == Lname || p.First_Name == Fname).ToList();
return View(patientList);
Thanks for the help!
I think the decision of what to do when multiple records are returned is up to you. You could have your View’s model be a List and display all of them in your view.
You would then have: