Reputation: 5349
How do i add first or default to my controller:
public ActionResult Index(string searchString)
{
var customers = from s in db.TicketDetails
select s;
if (!String.IsNullOrEmpty(searchString))
{
//search criteria
customers = customers.Where(s => s.SupportRef.Contains(searchString));
}
return View(db.TicketDetails.ToList());
}
I need to make sure my results only return 1 record. If they return null
then I need to pass in dummy values.
Upvotes: 0
Views: 347
Reputation: 37299
Make sure how many items you have returning from the query.
All together you can write it this way:
public ActionResult Index(string searchString)
{
var defaultReturnValue = //you default dummy object
if(String.IsNullOrEmpty(searchString))
return View(defaultReturnValue);
var customers = (from s in db.TicketDetails
where s.SupportRef.Contains(searchingString)
select s).Take(2).ToList(); // execute query here so not to execute it twice
return View(customers.Count > 1 ? defaultReturnValue :
customers.FirstOrDefault() ?? defaultReturnValue);
}
I've added the Take(2)
so the generated query will take up to 2 records and so, in a case that there is more than a single record it will still not bring all of them
Upvotes: 2