User00000034
User00000034

Reputation: 7

Using multiple checkboxes for same property to filter data in MVC .NET

I am following the ASP.NET MVC 5 tutorial at http://www.asp.net/mvc/overview/getting-started/introduction/getting-started

This tutorial creates a basic database containing movie objects, of which the properties are title, release date, genre, and price.

I have two checkboxes, one for movies who's price is 5, and one for 10.

What I have works fine if only one of the checkboxes is selected, but if both are selected (I am trying to list movies who's price is 5 and movies who's price is 10) then nothing is shown in the view.

Am I way off?

Model:

 public class Movie
 {
    public int ID { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }

 }

public class MovieDBContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
}

Controller:

 public class MoviesController : Controller
{
    private MovieDBContext db = new MovieDBContext();



    public ActionResult Index(bool movieCost5 = false, bool movieCost10 = false)
    {

        var movies = from m in db.Movies
                     select m;



        if (movieCost5 == true && movieCost10 == false)
        {
            movies = movies.Where(x => x.Price == 5);
        }
        else if (movieCost5 == true && movieCost10 == true)
        {
            movies = movies.Where(x => x.Price == 5 && x.Price == 10);
        }

        else if (movieCost5 == false && movieCost10 == true)
        {
            movies = movies.Where(x => x.Price == 10);
        }

        return View(movies);
    }
}

Upvotes: 0

Views: 1828

Answers (1)

decPL
decPL

Reputation: 5402

x.Price == 5 && x.Price == 10

This means you're looking for movies with price both 5 and 10 at the same time - unless you have some custom logic for comparing your Price with integers, this will never work.

You're probably looking for:

x.Price == 5 || x.Price == 10

(logical OR not logical AND)

EDIT :

When working with similar problems it is often useful to try to narrow down your issue, which is something you could have done on your own. If you believed there was some issue with how your checkbox logic works, why not test it on a simpler case, e.g.:

if (movieCost5 == true && movieCost10 == false)
{
   movies = new[] { new Movie { Title = "movieCost5 works correctly" } };
}
else if (movieCost5 == true && movieCost10 == true)
{
   movies = new[] { new Movie { Title = "YAY! Both work as well!" } };
}
else if (movieCost5 == false && movieCost10 == true)
{
   movies = new[] { new Movie { Title = "movieCost10 works correctly" } };
}

Upvotes: 3

Related Questions