Reputation: 57469
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
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
Reputation: 24108
I would:
MinPrice
, MaxPrice
nullable, so that I can only filter either on Min or Max and not on both.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
Reputation: 53155
You can check ModelState.Count. If ModelState.Count == 0 then no values were set to your model during binding.
Upvotes: 3