What are the different or best ways I can implement a simple product dropdown in ASP.NET MVC, that redirect the user to a new product when they pick from the dropdown ?
I have currently have my primary mapping rule :
routes.MapRoute(
"Product",
"Products/{sku}",
new { controller = "Products", action = "ViewProduct", sku = "1001" }
);
This allows me to enter a URL like this to view my product:
/Products/1002
I have a dropdown on my page which represents a list of products, and allows you to select form the list. (The sku
parameter is the same name as the parameter in my controller's ViewProduct method) :
<% using (Html.BeginForm("ViewProduct", "Products"))
{ %>
<%= Html.DropDownList("sku", ViewData.Model.ProductsList)%>
<%= Html.SubmitButton() %> <!-- just using a button now since its easier -->
<% } %>
This form targets the 'ViewProduct' command that I have in my controller (which is a full view that renders a product's information page).
The problem is that the HTML generated (when I view the HTML for /Products/1002
) looks like this:
<form action="/Products/1002" method="post">
<select id="sku" name="sku">
<option value="1003">Product 1003</option>
<option value="1002">Product 1002</option>
<option value="2001">Product 2001</option>
</select>
<input type="submit" />
</form>
It has gone and created the action link based upon the current URL (i guess it really had no choice). The problem is that when my controller is called after clicking 'Submit' it just goes ahead and fetches product 1002 again - and doesnt get overridden by the 'sku' parameter from the form.
Now, the actual value is available in Request.Params["sku"]
, but obvously its a pretty horrible practice to go and try to get it from there.
One extremely convoluted solution is as follows - create a different routing rule which hits a different controller method RedirectProduct
.
routes.MapRoute(
"Product Redirect",
"Products/RedirectProduct",
new { controller = "Products", action = "RedirectProduct" }
);
Then the action to my form can simply be :
<% using (Html.BeginForm("RedirectProduct", "Products")) { %>
This hits my controller method, which has access to 'sku' (the correct one I want that is coming from the form params). The controller method just redirects to /Products/XXX .
public ActionResult RedirectProduct(string sku)
{
return new RedirectResult("/Products/" + sku);
}
I don't like this solution at all - but I wanted to at least present what I had so far. I dont like adding extra mapping rules like this, and having to create different action names when I really just have one.
I'm sure theres 50 different ways I could do this -- hence me asking the question on stackoverflow -- to try and figure which is best. Unfortunately at this time the documentation for Forms handling for MVC that I've found is pretty simple.
PS. I'm not primarily looking for a JQuery solution (I want to master 'pure MVC' first) but I'd welcome one.