2

In an MVC application in the controller I use Entity Framework and LINQ. I'm storing 10 records in a variable then, binding them to the model. But if there are no records I'm getting error

Index was out of range. Must be non-negative and less than the size of the collection.

While I handled null exception in view. I'm getting compile time error

Cannot initialize implicitly typed variable with an 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() as 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());
        }
    }
}
3
  • 3
    Like you do with anything else...put a conditional or a guard clause in place. Commented Apr 7, 2017 at 11:48
  • What are you passing to view "items"? Commented Apr 7, 2017 at 12:49
  • view items passing to a model. Commented Apr 7, 2017 at 13:33

2 Answers 2

2

The problem is that the code below is recognized as Razor code while you are probably expecting it to be Javascript code:

var   myLatLng = { lat:  @Model[0].latitude.ToString(), lng: @Model[0].longitude.ToString() };

Simply add @: before the statements you want to be ignored by Razor:

@if (Model != null)
{
    @: var myLatLng = { lat:  @Model[0].latitude.ToString(), lng: @Model[0].longitude.ToString() };
}
else
{
    @: var myLatLng = { lat:0, lng:0 };
}
Sign up to request clarification or add additional context in comments.

1 Comment

ur code is correct but @if (Model != null) not working in my case . even though model count = 0 . its entering into this loop.unble to handle exception while model is null.
1

Just check if the list is > 0

@if (Model != null && Model.Count >0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.