c# - how to handle null exception if model is null , how to handle it in view in mvc? -


in mvc application in controller use entity framework , linq. i'm storing 10 records in variable then, binding them model. if there no records i'm getting error

index out of range. must non-negative , less size of collection.

while handled null exception in view. i'm getting compile time error

cannot initialize implicitly typed variable array initializer.

view:

  function initmap() {             var labels = '12345678910';             var labelindex = 0;             @if (model != null)                    {                        var   mylatlng = { lat:  @model[0].latitude.tostring(), lng: @model[0].longitude.tostring() };                    }             else                    {                           var mylatlng = { lat:0, lng:0};//bharat seva ashram                       } 

controller:

list<assettrackerviewmodel> model = new list<assettrackerviewmodel>(); /// pir 1 //rad:dn try {     webrequest req = webrequest.create(@"https://url");     req.method = "get";     req.headers["authorization"] = "basic " + "pwd==";     httpwebresponse resp = req.getresponse() httpwebresponse;     var encoding = resp.characterset == "" ? encoding.utf8 : encoding.getencoding(resp.characterset);     using (var stream = resp.getresponsestream())     {         var reader = new streamreader(stream, encoding);         var responsestring = reader.readtoend();        **//here "items" im getting null / empty**         var items = pirs.where(a => !a.dataframe.endswith("aaaaaaaaaaa="))                                          .groupby(a => a.dataframe.substring(a.dataframe.length - 12))                                          .select(g => g.first())                                          .orderbydescending(a => a.timestamp)                                          .take(10);          foreach (var item in items)         {             byte[] data = convert.frombase64string(item.dataframe.tostring());         }     } } 

the problem code below recognized razor code while expecting javascript code:

var   mylatlng = { lat:  @model[0].latitude.tostring(), lng: @model[0].longitude.tostring() }; 

simply add @: before statements want ignored razor:

@if (model != null) {     @: var mylatlng = { lat:  @model[0].latitude.tostring(), lng: @model[0].longitude.tostring() }; } else {     @: var mylatlng = { lat:0, lng:0 }; } 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -