How to create razor dropdownlist in .net mvc via ajax?

2

I would like to dynamically load my dropdownlist without submitting the page! my project is in .net mvc! architecture

 @Html.Label("Categoria do Veiculo: ")
    @Html.DropDownListFor(v => v.CodigoCategoriaVeiculo,Model.TipoModeloEquipamentosList)

I would like it to load via ajax!

    
asked by anonymous 20.02.2015 / 20:32

3 answers

4

As suggested by jHonathan you can make an AJAX request, here are some important things to do:

Controller

[HttpPost]
public JsonResult GetSubValor(Int32 valor)
{
    return Json(this.GetSubValores(valor));
}

private List<SubValorModel> GetSubValores(Int32 valor)
{
    var subValores = new List<SubValorModel>();
    if (valor == default(Int32))
        return subValores;

    valor = valor - 1;
    var startIndex = (valor * 10) + 1;
    for (int indice = startIndex; indice < startIndex + 10; indice++)
    {
        var tmp = indice.ToString("000");
        subValores.Add(new SubValorModel {
            SubValorID = indice,
            Descricao = "Sub Valor " + tmp
        });
    }
    return subValores;
}

JavaScript

var valor = $("#Valor");
var subValor = $("#SubValor");
valor.change(function () {
    var request = { "valor": valor.val() };         
    $.post("/Home/GetSubValor/", request, function(subValores) { 
        subValor.empty();
        var option = $("<option>").text("Selecione um SubValor");
        subValor.append(option);
        $.each(subValores, function (indice, item) { 
            option = $("<option>", { "value": item.SubValorID }).text(item.Descricao);
            subValor.append(option);
        });
    }, "json");
});

If you need, you can study the full example below.

Model

using System;
using System.ComponentModel.DataAnnotations;

namespace MvcApp
{
    public class Model
    {
        public Int32 Valor { get; set; }        
        public Int32 SubValor { get; set; }
    }

    public class ValorModel
    {
        public Int32 ValorID { get; set; }      
        public String Descricao { get; set; }
    }

    public class SubValorModel
    {
        public Int32 SubValorID { get; set; }

        public String Descricao { get; set; }
    }
}

Control

using System;
using System.Web.Mvc;
using System.Linq;
using System.Collections.Generic;

namespace MvcApp
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            var model = new Model();
            this.CreateLists(model);
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(Model model)
        {
            this.CreateLists(model);
            return View(model);
        }

        [HttpPost]
        public JsonResult GetSubValor(Int32 valor)
        {
            return Json(this.GetSubValores(valor));
        }

        private void CreateLists(Model model)
        {
            ViewBag.Valor = new SelectList(this.GetValores(), "ValorID", "Descricao", model.Valor);
            ViewBag.SubValor = new SelectList(this.GetSubValores(model.Valor), "SubValorID", "Descricao", model.SubValor);
        }

        private List<ValorModel> GetValores()
        {
            var valores = new List<ValorModel>();
            for (int indice = 1; indice <= 10; indice++)
            {
                var tmp = indice.ToString("000");
                valores.Add(new ValorModel {
                    ValorID = indice,
                    Descricao = "Valor " + tmp
                });
            }
            return valores;
        }

        private List<SubValorModel> GetSubValores(Int32 valor)
        {
            var subValores = new List<SubValorModel>();
            if (valor == default(Int32))
                return subValores;

            valor = valor - 1;
            var startIndex = (valor * 10) + 1;
            for (int indice = startIndex; indice < startIndex + 10; indice++)
            {
                var tmp = indice.ToString("000");
                subValores.Add(new SubValorModel {
                    SubValorID = indice,
                    Descricao = "Sub Valor " + tmp
                });
            }
            return subValores;
        }
    }
}

View

@model MvcApp.Model
@{
    Layout = null;
}

<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->

<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>

    <body>
        @using (Html.BeginForm())
        {

            <div>
                @Html.LabelFor(model => model.Valor)
                @Html.DropDownList("Valor", ViewBag.Valor as SelectList, "Selecione um Valor")
            </div>
            <div>               
                @Html.LabelFor(model => model.SubValor)
                @Html.DropDownList("SubValor", ViewBag.SubValor as SelectList, "Selecione um SubValor")             
            </div>  
            if (Model.Valor != 0) {
            <div>
                Valor Enviado:
                <input type="text" readonly="readonly" disabled="disabled" value="@Model.Valor" />
                <input type="text" readonly="readonly" disabled="disabled" value="@Model.SubValor" />               
            </div>
            }
            <input type="submit" value="Enviar" />
        }
        <!-- JS includes -->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {          
                var valor = $("#Valor");
                var subValor = $("#SubValor");
                valor.change(function () {
                    var request = { "valor": valor.val() };         
                    $.post("/Home/GetSubValor/", request, function(subValores) { 
                        subValor.empty();
                        var option = $("<option>").text("Selecione um SubValor");
                        subValor.append(option);
                        $.each(subValores, function (indice, item) { 
                            option = $("<option>", { "value": item.SubValorID }).text(item.Descricao);
                            subValor.append(option);
                        });
                    }, "json");
                });
            });
        </script>
    </body>
</html>
    
27.02.2015 / 13:36
0

Just do an ajax request and return to Json for example.

See this question: link

    
26.02.2015 / 23:08
0

As Jhonathan suggested should work, however you can do so too:

PartialView: DropDown.cshtml

@model IEnumerable<SelecListItem>

<label>Drop Down</label>
@Html.DropDownList("NomeCampo", Model, "Selecione um item")

Controller

public PartialViewResult GetDropDown(int id)
{
    var itens = new List<SelectListItem>();

    itens.Add(new SelectListItem() {Text = "Ajuda", Value = 1});

    return PartialView("DropDown", itens);
}

And make an ajax request and put the return inside a container.

    
27.02.2015 / 13:56