Reputation: 1666
I have the DropDownList which has two items. When I select the second one, it flashes it then goes back the first one immediately.
@Html.DropDownListFor(m => m.SelectedProduct, new SelectList(Model.Products, "ProductCode", "ProductName",Model.SelectedProduct),new { @class = "form-control" })
My controller code.
public ActionResult Index(int id, string productName)
{
var model = new ProductModel
{
Product = ProductService.GetProducts()
};
var view = "Something";
model.SelectedProduct = productName;
if(productName =="another")
view = "another";
return View(view, model);
}
The type of Model.Products
is IList<Product>
.
public class Product
{
public string ProductName {get;set;}
public string ProductCode {get;set;}
}
I saw this link, but I don't have ViewData
in my controller. So help me please.
My client side code:
$(document).ready(function () {
$("#SelectedProduct").change(function () {
var selectedValue = $(this).find('option:selected').text();
window.location.href = "@(Url.RouteUrl("MyRoute", new { id = Model.id }))/" + encodeURI(selectedValue);
});
Upvotes: 0
Views: 516
Reputation: 9463
The problem is with the selected item (4th parameter) that is passed to
new SelectList(Model.Products, "ProductCode", "ProductName", Model.SelectedProduct)
.
This expects that Model.SelectedProduct
holds the Value
of an item in the SelectList.
But your JS code passes var selectedValue = $(this).find('option:selected').text();
which is the Name
.
Change this to
var selectedValue = $(this).find('option:selected').val();
to pass along the ProductCode.
Upvotes: 1