asp.net mvc - Value cannot be null -


i have written asp.net mvc code crud while updating,deleting , details page throwing error value can not null.my code 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 model

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 because variable alb , album showing me null value not getting id. suggest me on this.

this because variable alb , album showing me null value not getting id

if there no record in database should handle gracefully in code. should have like:

var alb=db.albums.firstordefault(x=>x.albumid==id); if (alb==null) {     // tempdata, simplest way give example     tempdata["error_msg"] = "the record not exists";        return redirecttoaction("index", "error"); } return view(alb); 

in errorcontroller

public actionresult index() {     viewbag.errormsg = tempdata["error_msg"];     return view(); } 

in view (index.cshtml) error controller

<h1>you have been, or trying be, naughty boy</h1> <p>@viewbag.errormsg</p> 

this not elegant solution though enough started. think important part of answer not code gave suggestion handle kind of situation (null values / missing or invalid records) in code.


Comments