DropDownList cascaded

8

I have this code but at the time of changing the option of the first DropDownList I get the following error:

  

undefined in the second DropDownList

 -El controlador-
public JsonResult ArticulosPorCategoria(int Id )
{
      var articulos = db.articulo.ToList().Where(p => p.Id_Categoria == Id);
      return Json(articulos, JsonRequestBehavior.AllowGet); 
}
    <script type="text/javascript">
        $(function () {
            $("#Categoria").change(function () {
                var val = $(this).val();
                var subItems="";
                $.getJSON("@Url.Action("ArticulosPorCategoria","Ventas")", {id:val} ,function (data){
                  $.each(data,function(index,item){
                    subItems+="<option value='"+item.Value+"'>"+item.Text+"</option>"
                  });
                  $("#Articulo").html(subItems)
                });
            });
        });
    </script>
@Html.DropDownList("Categoria", ViewBag.Categoria as SelectList, 
htmlAttributes: new { @class = "form-control" })

@Html.DropDownList("Articulo", ViewBag.Artics as SelectList, 
htmlAttributes: new { @class = "form-control" })

That's how I get it:

    
asked by Xique 24.08.2016 в 00:17
source

1 answer

6

I already solved it in case someone needs something similar in the future

Controller

public JsonResult ArticulosPorCategoria(int Id )
{
    var articulos = db.articulo.ToList().Where(p => p.Id_Categoria == Id);
    return Json(new SelectList(articulos, "Id", "Nombre")); 
}

Script

<script type="text/javascript">

    $(document).ready(function () {
        $("#Categoria").change(function () {
            $("#Articulo").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("ArticulosPorCategoria")',
                dataType: 'json',
                data: { id: $("#Categoria").val() },
                success: function (articulos) {
                    $.each(articulos, function (i, articulo) {
                        $("#Articulo").append('<option value="' + articulo.Value + '">' +  
                        articulo.Text + '</option>');   

                    });
                },
            })
        });
    });
</script>
@Html.DropDownList("Categoria", ViewBag.Categoria as SelectList,htmlAttributes: new { @class = "form-control" })

@Html.DropDownList("Articulo", ViewBag.Artics as SelectList,htmlAttributes: new { @class = "form-control" })
    
answered by 24.08.2016 / 17:30
source