Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to allow nulls but... "Nullable object must have a value"

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);
    }
like image 610
ilirvg Avatar asked Dec 27 '12 10:12

ilirvg


People also ask

Can a nullable be null?

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.

What is a nullable value?

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.

What is difference between null and Nullable?

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.

What is nullable value type in C#?

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.


1 Answers

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
like image 177
Sergey Berezovskiy Avatar answered Sep 24 '22 08:09

Sergey Berezovskiy