Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

VaryByParam for MVC Model

I have below search model for my MVC application.

public class SearchFilters
{
    public SearchFilters()
    {
        MinPrice = "10000";
        MaxPrice = "8000000";
    }
    public IEnumerable<SelectListItem> Categories { get; set; }
    public string[] CategoriesId { get; set; }

    public IEnumerable<SelectListItem> Locations { get; set; }
    public string[] LocationID { get; set; }

    public IEnumerable<SelectListItem> Status { get; set; }
    public string[] StatusID { get; set; }

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

Now when the user searches for any record, It will pass the selected params through model data and my get request is as below:

[HttpGet]
public ActionResult Search([Bind(Prefix = "searchModel")]SearchFilters smodel)
{
    CategoryViewModel model = new CategoryViewModel();
    model = _prepareModel.PrepareCategoryModel("Search", smodel);
    if (model.projects.Count == 0)
    {
        return Json(new { message = "Sorry! No result matching your search", count = model.projects.Count }, JsonRequestBehavior.AllowGet);
    }
    return PartialView("_CategoryView", model);
}

If the parameter passed was a string or int, I could have set VaryByParam = "param" or if multiple it would be set with ';' separated values. But how would I cache the complex model param here?

Upvotes: 1

Views: 471

Answers (1)

Alex Art.
Alex Art.

Reputation: 8781

According to the MSDN VaryByParam value should be

a semicolon-separated list of strings that correspond to query-string values for the GET method, or to parameter values for the POST method.

So for complex model you need to specify all its properties separated by semicolon. You also need to take into consideration the binding prefix that you have. Since your HttpGet request most probably look like this:

http://../someUrl?searchModel.MinPrice=1&searchModel.MaxPrice=5&searchModel.CategoriesId=10&searchModel.LocationID=3&searchModel.StatusID=8

The VaryByParam value should be:

VaryByParam="searchModel.MinPrice;searchModel.MaxPrice; searchModel.CategoriesId;searchModel.LocationID;searchModel.StatusID"

Upvotes: 2

Related Questions