fill in input from dropdownlist selection ASP.NET MVC5

2

Hello StackOverFlow colleagues, I have the following question, how can I load or give a value to an input when selecting an option in a select or dropdownlist?

my create controller is as follows:

// GET: Collaborators/Create
        public ActionResult Create()
        {
            var lideres = (from p in db.Collaborators
                                  where p.grupo_lider == "SI"
                                  select p).ToList();

            ViewBag.lideres = lideres.Select(p => new SelectListItem() { Value = p.nombres, Text = p.nombres }).ToList();

            ViewBag.CompanyID = new SelectList(db.Companies, "CompanyID", "compania");
            return View();
        }

Part of my view:

<div class="form-group">
            @Html.LabelFor(model => model.lider, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.lider, (List<SelectListItem>)ViewBag.lideres, "Selleccione un líder", new{ @class = "form-control" })
                @Html.ValidationMessageFor(model => model.lider, "", new { @class = "text-danger" })
</div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.cargo_lider, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.cargo_lider, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.cargo_lider, "", new { @class = "text-danger" })
            </div>
        </div>

Part of my model with the most relevant parts referring to my doubt:

[Display(Name = "Lider")]
public string lider { get; set; }
[Display(Name = "Cargo Lider")]
public string cargo_lider { get; set; }
[Display(Name = "Cargo")]
public string cargo { get; set; }

I explain exactly what I need, now my dropdownList that has as model model.lider shows the names of the users whose group_lider is equal to "SI" in the controller shows the query that I made, what I need now is to load the input @Html.EditorFor(model => model.cargo_lider, new { htmlAttributes = new { @class = "form-control" } }) with the charge according to the name or the user that is selected in the dropdownlist, taking into account that this data is in the column cargo of the db.collaborators, and I need to load it in the input with modelo.cargo_lider .

I remain attentive to questions, answers and so on.

Ajax Current Code:

$('#iddropdownlist').change(function () {
            var url = "/Collaborators/BuscarCargoLider?claveLider=" + $('#iddropdownlist option:selected').val();
            $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                async: true,
                success: function (result) {
                    var lider;
                    if (result != null && result.length > 0) {
                        lider= JSON.parse(result);
                    }
                    if (lider!= null ) {                    
                        $('#idinput').val(lider);//cargo debe ser la propiedad de la clase lider donde se almacena el cargo del lider 
                    }                
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("error al consultar datos del lider");
                }
            });        
        });

Controller:

[HttpGet]
        public JsonResult BuscarCargoLider(string claveLider)
        {
            try
            {
                var lider = (from p in db.Collaborators
                             where p.nombres == claveLider
                             select p.cargo).ToList();

                return Json(lider, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
            }
            return Json("", JsonRequestBehavior.AllowGet);
        }
    
asked by ByGroxD 17.05.2017 в 15:24
source

2 answers

2

in the controller:

[HttpGet]
    public JsonResult BuscarCargoLider(string claveLider)
    {
        try
        {
            var lider = tuconsulta(claveLider);                
            return Json(lider, JsonRequestBehavior.AllowGet);//lider es un objeto con la propiedades que tienes en la base de datos, espero ya tengas un objeto asi, la funcion tuconsulta es la que va a ir a buscar los datos del lider a la base de datos la debes de tener en algun lado y sólo mandarla llamar aqui
        }
        catch (Exception ex)
        {

        }
        return Json("", JsonRequestBehavior.AllowGet);
    }        

In the view:

$('#iddropdownlist').change(function () {
    var url = "/nombreControlador/BuscarCargoLider?claveLider=" + $('#iddropdownlist option:selected').val();
$.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        async: true,
        success: function (result) {
            var lider;
            if (result != null && result.length > 0) {
                lider= JSON.parse(result);
            }
            if (lider!= null ) {                    
                $('#idinput').val(lider.cargo);//cargo debe ser la propiedad de la clase lider donde se almacena el cargo del lider 
            }                
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("error al consultar datos del lider");
        }
    });        
}
    
answered by 18.05.2017 / 00:33
source
1

In the view:

<script type="text/javascript">
$(document).ready(function () {
    $('#iddropdownlist').change(function () {
        $('#idinput').val($('#iddropdownlist option:selected').val());
    }
});
</script>

To put an id to dropdownlist and input

@Html.DropDownListFor(model => model.lider,(List<SelectListItem>)ViewBag.lideres, "Selleccione un líder", new{@id="iddropdownlist" @class = "form-control" })

@Html.EditorFor(model => model.cargo_lider, new { htmlAttributes = new { @id="idinput" @class = "form-control" } })
    
answered by 17.05.2017 в 23:32