I am trying to allow nulls in my drop down list, in my database table I have set allow nulls for that specific field which is int, but when I run the code I get error saying "Nullable object must have a value", I think problem may be in ModelState.
Controller
[HttpPost]
public ActionResult Edit(Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
Loan w = new Loan()
{
StudentID = student.StudentID,
ISBN = student.ISBN.Value,
};
db.Loans.Add(w);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ISBN1 = new SelectList(db.Books, "ISBN", "Titulli", student.ISBN);
return View(student);
}
Conversion from a nullable value type to an underlying type At run time, if the value of a nullable value type is null , the explicit cast throws an InvalidOperationException.
Nullable types represent the Null value as well the actual range of that data type. Like the int data type can hold the value from -2147483648 to 2147483647 but a Nullable int can hold the value null and range from -2147483648 to 2147483647.
A type is said to be nullable if it can be assigned a value or can be assigned null, which means the type has no value whatsoever.
The Nullable type allows you to assign a null value to a variable. Nullable types introduced in C#2.0 can only work with Value Type, not with Reference Type. The nullable types for Reference Type is introduced later in C# 8.0 in 2019 so that we can explicitly define if a reference type can or can not hold a null value.
You are getting this error when trying to get value of nullable object, which do not have value. If Loan.ISBN
property is not nullable then you should provide default value for that property
ISBN = student.ISBN.HasValue ? student.ISBN.Value : defaultValue
// or ISBN = student.ISBN ?? defaultValue
// or ISBN = student.ISBN.GetValueOrDefault()
If Loan.ISBN
property is nullable, then simply assign student.ISBN
without accessing Value
of nullable type
ISBN = student.ISBN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With