Load DropDownList via ajax

2

I work in an ASP MVC project, I am trying to create an entity Material for which I have the following Model:

public class MaterialViewModel
{
    [Display(Name = "Número de Registro")]
    public int MaterialId { get; set; }

    [Display(Name = "Descripción")]
    public string Descripcion { get; set; }

    [Display(Name = "Categoría")]
    public int CategoriaId { get; set; }

    ***public SelectList CategoriasMaterialViewModel { get; set; }***

    [Display(Name = "Unidad de medida")]
    public int UnidadMedidaId { get; set; }

    ***public SelectList UnidadesDeMedidaViewModel { get; set; }***

    public ImagenViewModel  ImagenViewModel { get; set; }
}

This model I use in the following view:

@model xxxx.WebUi.Models.MaterialViewModel
@{
    ViewBag.Title = "Nuevo material";
}

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Content/js/fileUpload.js"></script>
<link href="~/Content/css/fileUpload.css" rel="stylesheet" />

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="content clearfix">
        <!-- Page Content -->
        <div id="page-wrapper">
            <div class="container-fluid">
                <div class="row">

                    <div class="panel panel-default">
                        <div class="panel-body">

                            <div class="form-horizontal">

                                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Descripcion, htmlAttributes: new { @class = "control-label col-sm-3" })
                                    <div class="col-sm-4">
                                        @Html.EditorFor(model => model.Descripcion, new { htmlAttributes = new { @class = "form-control", maxlength = "200" } })
                                        @Html.ValidationMessageFor(model => model.Descripcion, "", new { @class = "label label-danger" })
                                    </div>
                                </div>

                                <div class="form-group">
                                    @Html.LabelFor(model => model.CategoriaId, htmlAttributes: new { @class = "control-label col-sm-3" })

                                    <div class="col-sm-4">
                                        @Html.DropDownListFor(x => x.CategoriaId, ***Model.CategoriasMaterialViewModel***, "<<<Seleccione>>>", new { @class = "form-control" })
                                        @Html.ValidationMessageFor(model => model.CategoriaId, "", new { @class = "label label-danger" })
                                    </div>
                                    <div>
                                        <a class="btn btn-info" data-modal="" data-target="#myModal" data-to data-toggle="modal" href='@Url.Action("Create", "CategoriasMateriales")' id="btnCreate" title="Nueva Categoría de Material"><span class="glyphicon glyphicon-plus"></span></a>
                                    </div>
                                </div>

                                <div class="form-group">
                                    @Html.LabelFor(model => model.UnidadMedidaId, htmlAttributes: new { @class = "control-label col-sm-3" })
                                    <div class="col-sm-4">
                                        @Html.DropDownListFor(model => model.UnidadMedidaId, ***Model.UnidadesDeMedidaViewModel***, "<<<Seleccione>>>", new { @class = "form-control" })
                                        @Html.ValidationMessageFor(model => model.UnidadMedidaId, "", new { @class = "label label-danger" })
                                    </div>

                                    <div>
                                        <a class="btn btn-info" data-modal="" data-target="#myModal" data-to data-toggle="modal" href='@Url.Action("CreatePopUp", "UnidadDeMedidas")' id="btnCreateUnidadMedida" title="Nueva Unidad de Medida"><span class="glyphicon glyphicon-plus"></span></a>
                                    </div>
                                </div>

                                <div class="form-group">

                                    <div class="col-sm-offset-3 col-sm-9">
                                        <input type="submit" class="btn btn-success" value="Guardar" />
                                        <a href='@Url.Action("Index")' class="btn btn-warning" role="button">Cancelar</a>
                                    </div>
                                </div>

                            </div>

                            <div>@Html.ActionLink("Regresar a la lista", "Index")</div>
                        </div>
                        <div class="panel-footer"></div>
                    </div>


                </div> <!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>  <!-- /.container-PAGE -->

    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Content/MyScripts")

}

<script src="~/Content/popup/xxxpopup.js"></script>

<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
    <div class="modal-dialog">
        <div class="modal-content">
            <div id='myModalContent'></div>
        </div>
    </div>
</div>

To load this view I use the following controller:

private SelectList GetCategoriasMaterial()
{
    return new SelectList(_categoriasRepository.GetAll(false), "CategoriaId", "Descripcion");
}

private SelectList GetUnidadesMedida()
{
    return new SelectList(_unidadesMedidasRepository.GetAll(false), "UnidadMedidaId", "Descripcion");
}


// GET: Materiales/Create
public ActionResult Create()
{
    var materialViewModel = new MaterialViewModel();
    materialViewModel.UnidadesDeMedidaViewModel = GetUnidadesMedida();
    materialViewModel.CategoriasMaterialViewModel = GetCategoriasMaterial();

    return View(materialViewModel);
}

With this script it is that I show and close the Pop-Up:

$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
    e.preventDefault();
    $('#myModalContent').load(this.href, function () {
        $('#myModal').modal({
            keyboard: true
        }, 'show');
        bindForm(this);
    });
    return false;
});
});

function bindForm(dialog) {
    $('form', dialog).submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            contentType: this.enctype,
            data: $(this).serialize(),
            success: function (result) {

                if (result.success) {
                    $('#myModal').modal('hide');
                    $('#replacetarget').load(result.url); 
                } else {
                    $('#myModalContent').html(result);
                    bindForm(dialog);
                }
            }
        });
        return false;
    });
}

Now, as you can see in the model the DropDownslist are loaded from the SelectList UnidadesDeMedidaViewModel and the CategoriasMaterialViewModel , in the view I have the option to add a unit of measure or a new category to be able to create the Corresponding material, for which I have the need that after the unit of measure or category is added the DropDownList will be refreshed with the new entity created and thus be able to continue with the flow.


How to achieve by means of AJAX to reload only the DropDown corresponding to the created entity (Unit of Measure or Category)?.

    
asked by jose luis garcia 30.04.2016 в 00:05
source

1 answer

1

It does something similar to me, for a Project called "Platypus", where the content of the DropDownList (html select) is "Units"

A Model like so (in \ Models \ HomeModel.cs):

public class HomeModel
{
    public DataTable Units { get; set; }
    . . .
}

A Controller like so (in \ Controllers \ HomeController.cs):

public class HomeController : Controller
{
    public ActionResult Index()
    {
        HomeModel model = new HomeModel();

        DataTable unitsDT = SQL.ExecuteSQLReturnDataTable(SQL.SelectUnitsQuery, CommandType.Text, null);
        model.Units = unitsDT;
        . . .

A View like this (in \ Views \ Home \ Index.cshtml):

@model Platypus.Models.HomeModel
@using System.Data
@{
    DataTable dtUnits = Model.Units;
    var units = from x in dtUnits.AsEnumerable()
                select new
                {
                    unit = x.Field<string>("unit")
                };
    
answered by 02.05.2016 в 16:45