Santosh
Santosh

Reputation: 9

Value cannot be null

I have written ASP.NET MVC Code for CRUD but while Updating,Deleting and Details the page is throwing the error as value can not be null.my code is as follows:

public ActionResult Edit(int id=0) 
            {  
                var alb=db.Albums.FirstOrDefault(x=>x.AlbumId==id);
                return View(alb);
            }
public ActionResult Detail(int id=0) 
        {
            var alb=db.Albums.Find(id);
            return View(alb);   
        }
public ActionResult Delete(int id=0) 
        {
            var album = db.Albums.Find(id);
            return View(album);

        }

and my Model is

public class Album
    {
        public int AlbumId { get; set; }
        public int GenreId { get; set; }
        public int ArtistId { get; set; }
        public string AlbumTitle { get; set; }
        public String Price { get; set; }
        public String AlbumArtUrl { get; set; }
        public Genre Genre { get; set; }
        public Artist Artist { get; set; }
    }

This is because the variable alb and album is showing me the null value its not getting any ID. so suggest me on this.

Upvotes: 0

Views: 480

Answers (1)

von v.
von v.

Reputation: 17118

This is because the variable alb and album is showing me the null value its not getting any ID

If there is no record in your database then you should handle it gracefully in code. You should have something like:

var alb=db.Albums.FirstOrDefault(x=>x.AlbumId==id);
if (alb==null) {
    // TempData, simplest way to give you an example
    TempData["error_msg"] = "the record does not exists";   
    return RedirectToAction("index", "error");
}
return View(alb);

in your ErrorController

public ActionResult Index() {
    ViewBag.ErrorMsg = TempData["error_msg"];
    return View();
}

in the view (Index.cshtml) for your error controller

<h1>You have been, or trying to be, a naughty boy</h1>
<p>@ViewBag.ErrorMsg</p>

This is not the most elegant solution though but good enough to get you started. I think the most important part of my answer is not the code I gave you but the suggestion to handle that kind of situation (null values / missing or invalid records) in code.

Upvotes: 1

Related Questions