I have an method in my controller (SurfaceController which is a specific Umbraco controller):
public class ProductListController : SurfaceController
{
public ActionResult GetCategoryProducts([ModelBinder(typeof(IntArrayModelBinder))] int[] categoryIds, int page = 1, int pageSize = 10)
{
int total = 0;
var products = ProductService.GetCategoryProducts(categoryIds, page, pageSize, out total);
return View("/Views/PartialView/ProductList.cshtml", products);
}
}
I then have the following ModelBinder, so I can create the request like "?categoryIds=1,2,3,4,5" instead of the default behaviour "?categoryIds=1&categoryIds=2&categoryIds=3&categoryIds=4&categoryIds=5".
public class IntArrayModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null || string.IsNullOrEmpty(value.AttemptedValue))
{
return null;
}
return value
.AttemptedValue
.Split(',')
.Select(int.Parse)
.ToArray();
}
}
This also means that it doesn't work when I send int[] as parameter to RenderAction, but it works when join the values to a comma delimited string.
@{ Html.RenderAction("GetCategoryProducts", "ProductList", new { categoryIds = new int[] { 1, 2, 3, 4, 5 }, pageSize = 50 }); }
@{ Html.RenderAction("GetCategoryProducts", "ProductList", new { categoryIds = string.Join(",", new int[] { 1, 2, 3, 4, 5 }), pageSize = 50 }); }
Can I somehow make it work with both int[] and string (split to int array for each comma), except changing "categoryIds" parameter in GetCategoryProducts to a string and then in this method split the string to an int array.
I would like if I can keep the signature GetCategoryProducts method.