This should be an easy one, but without ViewState, I’m clueless here (I’ve been babied with WebForms for too long, I know!).
My scenario:
View
@foreach (var product in Model.Products)
{
<tr>
<td>@Html.ActionLink("Compare", "Compare", new { id = product.ProductId })</td>
</tr>
}
Controller
public ActionResult Compare(int id = 0)
{
var product = SelectProduct(id); // selects the product from a list of cached products.
if (product != null)
{
// _productDetails is a Model specifically for my View.
_productDetails.ComparedProducts.Add(product);
}
return View("Index", _productDetails);
}
Obviously, when you click on “Compare” for each item, it’ll add to the the ComparedProducts list. But, with there being no ViewState, this will get cleared on every page refresh and lose the last product. I want products to be kept in this ComparedProducts list, but how?
I’m guessing they need to be appended to the querystring, so /Carousel/Compare/?id=2122,1221,1331,1333 etc. If so, how is this possible?
Thanks in advance.
Updated
If I did want to go the query string route, how do I do this?
I’ve tried:
<td>@Html.ActionLink("Compare", "Compare", new { id = product.ProductId, compared = Model.ComparedProducts.Select(a => a.ProductId) })</td>
But that brings out:
compared=System.Linq.Enumerable%2BWhereSelectListIterator`2[Product%2CSystem.Int32]
Which I’d expect really. I guess I’d make yet a further ViewModel property and simply store the Compared Id’s in there to not have much business logic within my View?
+1 for your relationship with webforms 🙂
I think from now on, you can start to keep state in the other ways you already know from webforms like Session State: http://msdn.microsoft.com/en-us/library/ms178581(v=vs.100).aspx
You are also right on the querystring, after all, if you want to keep things simple, is better to use the simplest methods , for instance:
EXAMPLE
you need the first action as HttpGet and now this one as httpPOST
Your view should react according to empty properties to display