Answered by:
error in HttpPost Controller

Question
-
User1571524970 posted
Hi guys,
I have a 2 Booking controllers (1 Get and 1 Post). I need the user to be able to enter data into 2 fields (RollNumber and Date) and press a submit button which will insert the selected date into a row in the Db which matches the RollNumber which was entered. Although when I press the submit button I get an error: Exception User-Unhandled 'Sequence contains no elememts' and I am not sure why.
Booking view:
My controllers:
namespace CampBookingSys.Controllers { public class SchoolController : Controller { private CampBookingSysDb db = new CampBookingSysDb(); // GET: School public ActionResult Index() { return View(); } [HttpGet] public ActionResult Booking() { var model = db.Dates.ToList(); return View(model); } [HttpPost] public ActionResult Booking(School model) { //insert Date into row in SchoolDb which matches RollNumber School school = db.Schools.First(m => m.RollNumber == model.RollNumber); ** THIS LINE THROWS EXCEPTION school.Date = model.Date; db.SaveChanges(); //make used date unavailable in datepicker Datepicker date = db.Dates.First(m => m.Date == model.Date); db.Dates.Remove(date); db.SaveChanges(); return View(model); } } }
Can anyone see why I am getting this error?
Cheers
Saturday, August 17, 2019 4:22 PM
Answers
-
User-474980206 posted
The error means now row found, as using First() requires at least one row. Use the debugger to determine what the roll number value is.- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Saturday, August 17, 2019 4:34 PM
All replies
-
User-474980206 posted
The error means now row found, as using First() requires at least one row. Use the debugger to determine what the roll number value is.- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Saturday, August 17, 2019 4:34 PM -
User1571524970 posted
Thanks bruce, I was sending in the incorrect RollNumber..
Saturday, August 17, 2019 5:26 PM -
User1571524970 posted
.
Saturday, August 17, 2019 5:49 PM -
User1520731567 posted
Hi darego,
If you are using LINQ or Lambda expression and getting error: InvalidOperationException “Sequence contains no elements”.
It means you are trying to retrieve an element from an empty sequence(may be returned by LINQ query.
There are some basic rules to handle this in LINQ or lambda expression.
This is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault().
This can also be caused by the following commands:
FirstAsync()
SingleAsync()
Last()
LastAsync()
Max()
Min()
Average()
More details,you could refer to:
https://techbrij.com/sequence-contains-no-elements-linq-lambda-error
Or add breakpoints on your code and check if your query has value in the database.
Best Regards.
Yuki Tao
Monday, August 19, 2019 7:50 AM