I have an ASP.NET MVC project without entity Framework and I have a view to add Customers, but when adding a new customer, I use when filling 2 fields DropDownList
(one Product Type and the other Product) that are already filled with information.
What I want to do is if I choose a product type, the second DropDownListFor
display only products that have that Product Type. I attach the code to see if you can help me.
this is controller
public ActionResult Create()
{
ClienteDBHanndle tpd = new ClienteDBHanndle();
List<SelectListItem> ListaProductos = new List<SelectListItem>();
var productos = tpd.GetProductos();
foreach (var item in productos)
{
ListaProductos.Add(new SelectListItem { Text = item.Nombre, Value = item.IDProducto.ToString() });
}
ViewBag.ListaProductos = ListaProductos;
var tipoproductos = tpd.GetTProductos();
List<SelectListItem> ListaTipoProductos = new List<SelectListItem>();
foreach (var item in tipoproductos)
{
ListaTipoProductos.Add(new SelectListItem { Text = item.Nombre, Value = item.IDTipoProducto.ToString() });
}
ViewBag.ListaTipoProductos = ListaTipoProductos;
return View();
}
These are the 2 DropDownList
<div class="col-md-10">
@Html.DropDownListFor(model => model.IDTipoProducto, (IEnumerable<SelectListItem>)ViewBag.ListaTipoProductos, "Selecciona tipo de producto", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.IDTipoProducto, "", new {@id = "IDTipoProducto", @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.IDproducto, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.IDproducto, (IEnumerable<SelectListItem>)ViewBag.ListaProductos, "Selecciona tipo de producto", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.IDproducto, "", new { @class = "text-danger" })
</div>
</div>
This is the model
namespace CTEMVC.ViewModel
{
public class ClientesViewModel
{
public int IDCliente { get; set; }
public int IDTipoProducto { get; set; }
public int IDproducto { get; set; }
public string Nombre { get; set; }
public int Clave { get; set; }
public int DiasCredito { get; set; }
public string Calle { get; set; }
public string Colonia { get; set; }
public string RFC { get; set; }
public string Estado { get; set; }
public string Pais { get; set; }
public short Activo { get; set; }
public string NombreProducto { get; set; }
}
}
To perform a Cascading DropDownList in the way you ask, you need to use jQuery , and more specifically the AJAX features .
In principle you need to create an Action in your Controller, which returns in JSON format the products of a certain type of product:
On the other hand, you must define a jQuery Script in your View , which calls the Action through AJAX
GetProductosList(int IDTipoProducto)
every time an element is selected in theDropDownList
@Html.DropDownListFor(model => model.IDTipoProducto
.The code would be something like this: