[RESOLVED]Query result that doesn’t make sense (to me)

Hallo , I’m trying  to get  a results base on day of the week  

By doing as follow .

 public PartialViewResult _course()
        {
            int myweekday = 1;

            DateTime dt = DateTime.Now;
            if (dt.DayOfWeek == DayOfWeek.Sunday) myweekday = 1;
            else if (dt.DayOfWeek == DayOfWeek.Monday) myweekday = 2;
            else if (dt.DayOfWeek == DayOfWeek.Tuesday) myweekday = 3;
            else if (dt.DayOfWeek == DayOfWeek.Wednesday) myweekday = 4;
            else if (dt.DayOfWeek == DayOfWeek.Thursday) myweekday = 5;
            else if (dt.DayOfWeek == DayOfWeek.Friday) myweekday = 6;
            else if (dt.DayOfWeek == DayOfWeek.Saturday) myweekday = 7;

            ///for Today
            var _sh = (from c in db.course select c).OrderBy(d => d.daynumber)
                .ThenBy(t => t.Time).Where(w => w.daynumber == myweekday);
            ///for the Next day 
            ///the result here should be 2 (today is sinday and sunday=1)
            ///
            ViewBag.next = (from c in db.course select c).Where(w => w.daynumber == (myweekday + 1))
                            .OrderBy(d => d.daynumber).ThenBy(t => t.Time);

My razor :

 @*the view bag should be null i have only results for sunday and thiis should point to manday*@
                @if (ViewBag.next != null)
                {
                    <h3>tomorrow</h3>
                    foreach (var item in ViewBag.next)
                    {
                        <h3>@ViewBag.Tomorrow</h3>


                        @item.daynumber
                        @item.Writer.Name
                    }
                }

how ever I’m getting the <h3>tomorrow</h3> display  any idea where is my mistake ?

The issue is that your ViewBag may not be null, but may simple exist with 0 items in it. You might want to change the code in your View to check if it is not null and not empty :

@if (ViewBag.next != null && ViewBag.next.Any())
{
       <!-- Omitted for brevity -->
}

You might be able to dramatically simplify your code as you can convert your DayOfWeek value into an integer using the Convert.ToInt32() method as seen below :

public PartialViewResult _course()
{
        // Get the current DateTime
        DateTime dt = DateTime.Now;

        // Since the Day of Week is 0-based, you'll need to increment it by 1
        int myweekday = Convert.ToInt32(dt.DayOfWeek) + 1;


        ///for Today
        var _sh = db.course.Where(w => w.daynumber == myweekday)
                           .OrderBy(d => d.daynumber)
                           .ThenBy(t => t.Time);

        ///the result here should be 2 (today is sinday and sunday=1)
        ViewBag.next = db.course.Where(w => w.daynumber == (myweekday + 1))
                                .OrderBy(d => d.daynumber)
                                .ThenBy(t => t.Time);
}

thanks a lot Mr. Rion,

i’m getting this Error by using Any

‘System.Data.Entity.Infrastructure.DbQuery<MyProjectName.Models.MyClassName>’ does not contain a definition for ‘Any’

 @if (ViewBag.next != null && ViewBag.next.Any())

Try including a ToList() to actually store a collection of your values in memory instead of a DbQuery :

///the result here should be 2 (today is sinday and sunday=1)
ViewBag.next = db.course.Where(w => w.daynumber == (myweekday + 1))
                        .OrderBy(d => d.daynumber)
                        .ThenBy(t => t.Time)
                        .ToList();

Rion Williams

Try including a ToList() to actually store a collection of your values in memory instead of a DbQuery :

///the result here should be 2 (today is sinday and sunday=1)
ViewBag.next = db.course.Where(w => w.daynumber == (myweekday + 1))
                        .OrderBy(d => d.daynumber)
                        .ThenBy(t => t.Time)
                        .ToList();

thanks Rion ,

but no, it’s not null .

john_mm

but no, it’s not null .

Right.

The ToList() call will result in an actual collection of results (in memory) and allow you to use the Any() extension method to check if the collection actually has any elements. You still need the appropriate null check to avoid any null-reference exceptions
when calling the Any() call.

<!-- This ensures that your next collection isn't null and actually contains at least one element -->
@if (ViewBag.next != null && ViewBag.next.Any())
{
     <h3>tomorrow</h3>
     <!-- This will iterate through each value within your collection (which is guaranteed to not be empty) -->
     @foreach (var item in ViewBag.next)
     {
            <h3>@ViewBag.Tomorrow</h3>
            @item.daynumber
            @item.Writer.Name
     }
}
 ViewBag.next = db.course.Where(w => w.daynumber == (myweekday + 1))
                          .OrderBy(d => d.daynumber)
                          .ThenBy(t => t.Time)
                          .ToList();

     @if (ViewBag.next != null && ViewBag.next.Any())
                {
                    <h3>bla</h3>

                    foreach (var item in ViewBag.next)
                    {


                    }

                }

[RuntimeBinderException: 'System.Collections.Generic.List<Hagadol12_8.Models.Course>' does not contain a definition for 'Any']
   CallSite.Target(Closure , CallSite , Object ) +137

john_mm

var stuff = db.course.Where(w => w.daynumber == (myweekday + 1))
                          .OrderBy(d => d.daynumber)
                          .ThenBy(t => t.Time)
                          .ToList();
 

 Validate stuff has stuff in it before working on ViewBag.  Because the viewbag is a dynamic object you’re playing hide and seek with what’s in the View bag.

Separate your concerns by putting all db results into stuff then work on stuffing the Viewbag.  Or better yet don’t even use the viewbag, use strongly typed views.

 

Hi,

john_mm

does not contain a definition for ‘Any’]

If not possible with Any() try with Count

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

john_mm

[RuntimeBinderException: 'System.Collections.Generic.List<Hagadol12_8.Models.Course>' does not contain a definition for 'Any']
   CallSite.Target(Closure , CallSite , Object ) +137

The Any() extension method should be available on any IEnumerable collections as long as you are using LINQ either explicitly in your View :

using System.Linq;

or by defining it within the web.config (to be available within your Views) :

<pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Linq" />
      </namespaces>
</pages>

If you are still continuing to encounter issues, you might consider using two of the following options :

  • Consider using the Count() method instead to see if that allows you to perform your check (to see how many values are available in your collection) :
    @if (ViewBag.next != null && ViewBag.next.Count() > 0)
    {
    
    }
  • Or an even easier approach would be to not use the ViewBag at all and actually pass in a strongly typed collection of your values to your View, which would allow you to access them via the Model using :
    // Build your collection of courses
    var courses = db.course.Where(w => w.daynumber == (myweekday + 1))
                           .OrderBy(d => d.daynumber)
                           .ThenBy(t => t.Time)
                           .ToList();
    
    // Pass your courses to your View
    return View("_YourViewName",courses);

    Doing this would allow you to access your courses using a strongly-typed collection instead of a dynamic ViewBag variable as seen below :

    <!-- Define your Model as a List of Course objects -->
    @model List<Hagadol12_8.Models.Course>
    
    <!-- Add your Logic -->
    @if (Model != null && Model.Any())
    {
    
        <!-- Loop through the strongly-typed Course objects in your Model -->
        @foreach (Hagadol12_8.Models.Course course in Model)
        {
    
        }
    }

you are using viewbag as a list data so have to check if there is any element in that list

Leave a Reply