I have a simple asp.net database program. I have a database called ChristmasTickets with data for: ID , BARCODENUM , NAME , EMAIL , ETC.
I can do a simple find if someone searched ID because its the key identifier.
ChristmasTickets ChristmasTickets = db.ChristmasTicketsDb.Find(id);
But in my HTML I am attempting to allow a user to search by BarcodeNum and not the ID. If the BarcodeNumber is found I am then trying to pull out the ID number.
I have this code so far, which does give me some help.
[HttpPost]
public ActionResult Search(SearchBarcode model, int BarcodeNum)
{
var FoundRecord = db.ChristmasTicketsDb.Where(x => x.BarcodeNum == BarcodeNum);
//get the ID from quote which does not work....
**int id = //get the id from FoundRecord.**
Trace.WriteLine("GET /ChristmasTickets/Edit/" + id);
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ChristmasTickets ChristmasTickets = db.ChristmasTicketsDb.Find(id);
if (ChristmasTickets == null)
{
return HttpNotFound();
}
return View(ChristmasTickets);
}
Can someone please point me in the right direction on how to pull out the ID number from FoundRecord.
Thanks
db.ChristmasTicketsDb.Where(x => x.BarcodeNum == BarcodeNum);
Will give you an IQueryable
of ChristmasTickets
.
Supposedly, there is one or none of these.
To get the actual element you are searching, you can use Linq FirstOrDefault()
(or SingleOrDefault
) instead of Where
:
var christmasTicket = db.ChristmasTicketsDb.FirstOrDefault(x => x.BarcodeNum == BarcodeNum);
if (christmasTicket != null)
{
// found !
// here you can take the id from christmasTicket
}
You can do it like this:
[HttpPost]
public ActionResult Search(SearchBarcode model, int BarcodeNum)
{
var FoundRecord = db.ChristmasTicketsDb.SingleOrDefault(x => x.BarcodeNum == BarcodeNum);
if (FoundRecord == null)
{
return HttpNotFound();
}
return View(FoundRecord);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.