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

Asked

Viewed 4,590 times

2

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

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

I’d like him to carry via ajax!

  • I could explain better what I meant by "without submitting the page"?

  • face on the same page I have a form that registers category. when registering the category I wanted to automatically populate the dropdownlist. without postback,refresh ,Ubmit via ajax

  • Would it be an option to do this by partial ? If it is, maybe it works and you do not need to refresh the page because it will be in charge of the partial.

  • @Hans, an Httphelper, is nothing more than a utility that writes a string, so you can just clear select with Javascript and add new options.

  • @Erik Could mi show an example of type? need to just see how the thing works

  • @Hansmiller take a look this dev media link that should help you ! But in short, partial pages are parts of pages that you can integrate to a main page without the need to refresh the whole page, like an iframe. Anyway, take a look who uses ajax too. I hope I helped.

Show 1 more comment

3 answers

4

as suggested by Jhonathan you can make an AJAX request, follow below the important passages to do this:

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 to, 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>

0

0

As Jhonathan suggested it should work, but you can do it 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.