Shawn Mclean
Shawn Mclean

Reputation: 57469

ASP.NET MVC: Check if binded model was actually passed to action

I have an action with a FilterModel passed to it. I use a search to pass the filter to the action or I call the action without passing a filter to it. When I call it normally, the filter is instantiated (which I did not expect to happen). How do I check that no filter was actually passed?

My model:

public class ProductFilterModel
{
    //Using a constructor so the search view gets a default value.
    public ProductFilterModel()
    {
        MinPrice = 500;
        MaxPrice = 1000;
    }

    public int MinPrice { get; set; }
    public int MaxPrice { get; set; }
}

Action:

public ActionResult Index(ProductFilterModel filter){
    //How do I check if no filter was passed?
}

The normal call to the action is: localhost/Products while a filtered call would be localhost/Products?MinPrice=5&MaxPrice=100

When my action receive a call normally, the filter gets defaulted to the values set above, so I cannot even check to see if MinPrice is 0 to know to load it normally.

Upvotes: 1

Views: 274

Answers (3)

Neal
Neal

Reputation: 4407

You are using the view model for both display and submission of data so why not use 2 constructors therefore making your intent far more explicit?

public class ProductFilterModel
{
  private int? _minPrice;
  private int? _maxPrice;

  public class ProductFilterModel( int defaultMinPrice, int defaultMaxPrice )
  {
    MinPrice = defaultMinPrice;
    MaxPrice = defaultMaxPrice;
  }

  public class ProductFilterModel()
  {
  }

  public int MinPrice
  {
    get { return _minPrice.HasValue ? _minPrice.Value ? 0; }
    set { _minPrice = value; }
  }

  public int MaxPrice
  {
    get { return _maxPrice.HasValue ? _maxPrice.Value ? Int32.MaxValue; }
    set { _maxPrice = value; }
  }

  public bool HasFilter
  {
    get { return _minPrice.HasValue || _maxPrice.HasValue; }
  }
}

Upvotes: 0

Dmytrii Nagirniak
Dmytrii Nagirniak

Reputation: 24108

I would:

  1. Make MinPrice, MaxPrice nullable, so that I can only filter either on Min or Max and not on both.
  2. Not set the default on the ViewModel.
  3. Set the default from the action, where the filter is created.
  4. Implement Index as following:

(Assume you always have the filter)

public ActionResult Index(ProductFilterModel filter){
    filter = filter ?? new ProductFilterModel();
    if (filter.MinPrice.HasValue)
       FilterOnMin();
    if (filter.MaxPrice.HasValue)
        AlsoFilterOnMax();
}

Upvotes: 1

Jon Galloway
Jon Galloway

Reputation: 53155

You can check ModelState.Count. If ModelState.Count == 0 then no values were set to your model during binding.

Upvotes: 3

Related Questions