I have two questions:
1) I would like to sort an array of products with select tag using controller. This is the controller:
public async Task<ViewResult> Index(string sortOrder,List<int> checkedTypes)
{
var products = from p in _db.Products
select p;
ViewData["PriceDesc"] = string.IsNullOrEmpty(sortOrder) ? "priceDesc" : "";
ViewData["NameDesc"] = string.IsNullOrEmpty(sortOrder) ? "nameDesc" : "";
switch(sortOrder)
{
case "priceDesc":
products = products.OrderByDescending(p => p.Price);
break;
case "nameDesc":
products = products.OrderByDescending(p => p.Name);
break;
default:
products = products.OrderBy(p => p.Name);
break;
}
return View(products);
}
When I used the code below, it works as intended:
<a asp-action="Index" asp-route-sortOrder="@ViewData["PriceDesc"]">
<button >Price desc</button>
</a>
<a asp-action="Index" asp-route-sortOrder="@ViewData["NameDesc"]">
<button >Name desc</button>
</a>
However, I want the sorting to be displayed as a dropdown(with tag),and without submit button, something like this:
<select name="sorting" id="sorting">
<option disabled selected>Select option</option>
<a asp-action="Index" name="priceDesc" asp-route-sortOrder="@ViewData["PriceDesc"]">
<option >Price: high to low</option>
</a>
<a asp-action="Index" name="nameDesc" asp-route-sortOrder="@ViewData["NameDesc"]">
<option>Name: descending</option>
</a>
</select>
But for some reason the code above just ignore tag and the tag just disappear. And nothing happens when I choose one of the options.
2) I also have checkbox that works. But when the products are filtered with the checkboxes, the checkboxes stay unchecked. This is the controller code:
if(checkedTypes.Count != 0){
products = products.Where(p => checkedTypes.Contains(p.TypeId));
}
and this is the view code:
@foreach(var type in types)
{
<input type="checkbox" name="checkedTypes" value="@type.id"/>
<label>@type.Name</label>
<br>
}
Is there a way to keep the checked checkboxes stay checked even after the filtering on controller is done?
Aucun commentaire:
Enregistrer un commentaire