Member 13044878 Ответов: 1

Элемент управления datepicker на jQuery работать первое время только на частичный вид


Я новичок в этом деле ASP.NET MVC5 - я работаю в проекте для школы, и у меня есть эта проблема.

Я открываю модал для добавления, редактирования и просмотра клиента, у меня есть текстовое поле даты рождения, я могу заставить его работать с выбором даты в первый раз, а затем, когда я сохраняю данные в БД и пытаюсь создать или отредактировать клиента, DatePicker не показывает календарь.

На главном экране я сгенерировал список клиентов с таблицами данных, используя обработку на стороне сервера для фильтрации, поиска и подкачки страниц, это работает нормально.

Я добавил нижнюю часть в верхней части этой таблицы, чтобы создать новых пользователей, а в строках таблицы я создаю новый столбец для параметров редактирования и просмотра.

Сейчас я хотел бы сосредоточиться на процессе создания нового клиента, думаю, найдя проблему здесь, я исправлю ее с помощью опции редактирования.

Это мой основной взгляд


 @model IEnumerable<aseguradorasweb.models.cliente>



    <div class="row">
        <div class="col-md-12">
            <div class="container" style="width: 100%; margin-top: 2%">
                <div class="panel panel-primary list-panel" id="list-panel">
                    <div class="panel-heading list-panel-heading">
                        <h1 class="panel-title list-panel-title">Clientes</h1>
                    </div>
                    
                        <span class="glyphicon glyphicon-new-window"></span> Nuevo Cliente
                    
                    <div class="panel-body">

                        
                            @* Aqui va la tabla generada por AJAX*@
                        <table id="cliente-data-table" class="table table-striped table-bordered" style="width: 100%"></table>

                    </div>
                </div>
            </div>
        </div>
    </div>

    @section Scripts
    {

        
        

            var assetListVM;
            $(function () {
                assetListVM = {
                    dt: null,

                    init: function () {
                        dt = $('#cliente-data-table').DataTable({
                            "serverSide": true,
                            "processing": true,
                            "ajax": {
                                "url":
                                "@Url.Action("ListClientes", "clientes")",

                            },
                            "columns": [
                                {
                                    "title": "Nombre",
                                    "data": "NOM_Cliente",
                                    "searchable": true,
                                    "sortable": true
                                },
                                {
                                    "title": "Apellido",
                                    "data": "APE_Cliente",
                                    "searchable": true,
                                    "sortable": true
                                },
                                {
                                    "title": "RFC",
                                    "data": "RFC_Cliente",
                                    "searchable": false,
                                    "sortable": false
                                },
                                {
                                    "title": "Email",
                                    "data": "Email_Cliente",
                                    "searchable": false,
                                    "sortable": false
                                },
                                {
                                    "title": "Telefono",
                                    "data": "Tel_Cliente",
                                    "searchable": false,
                                    "sortable": false
                                },
                                {
                                    "title": "Celular",
                                    "data": "Cel_Cliente",
                                    "searchable": false,
                                    "sortable": false
                                },
                                {
                                "title": "Acciones",
                                "data": "ID_Cliente",
                                "searchable": false,
                                "sortable": false,
                                "render": function (data, type, full, meta) {
                                    return '<a href="@Url.Action("Edit","clientes")?id=' + data + '" class="EditCliente"><i class="glyphicon glyphicon-pencil"></i></a>  <a href="@Url.Action("Details","clientes")?id=' + data + '" class="DetailsCliente"><i class="glyphicon glyphicon-eye-open"></i></a>';
                                }
                                }
                            ],
                            "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
                        });
                    }
                }
                // initialize the datatables
                assetListVM.init();

            });

            //Acciones para crear un nuevo cliente

            $("#btnCreateCliente").on("click", function () {

                var url = $(this).data("url");

                $.get(url, function (data) {
                    $('#createClienteContainer').html(data);
                    $('#createClienteModal').modal('show');
                    $("#FEC_NAC_Cliente").datepicker({
                    dateFormat: 'yy-mm-dd',
                    changeMonth: true,
                    changeYear: true,
                    yearRange: "-100:+0"
                });
                });

            });

            function CreateClienteSuccess(data) {

                if (data != "success") {
                    $('#createClienteContainer').html(data);
                    return;
                }
                $('#createClienteModal').modal('hide');
                $('#createClienteContainer').html("");
                //dt.ajax.reload();
                //location.reload();

            }
        
    }



<div class="modal fade" id="createClienteModal">
    <div id="createClienteContainer">
    </div>
</div>


When the bottom for NEW CLIENT is click, I go to the control and I get the Model

public ActionResult Create()
        {
            var model = new cliente();

            return View("_CreateClientePartial", model);
        }

and I show the partial view , The partial view is shown on a MODAL, inside of the modal I have TAB PAnels and the field call FEC_NAC_Cliente (Date of Birth).

Here is the Partial View



@model AseguradorasWeb.Models.cliente
@{
    Layout = null;
}



<div class="modal-dialog modal-lg">
    <div class="modal-content">
    <div class="modal-header">
        ×
        <h4 class="modal-title">Agregar Cliente</h4>
    </div>
    @using (Ajax.BeginForm("Create", "clientes", new AjaxOptions
    {   HttpMethod = "Post",
        OnSuccess = "CreateClienteSuccess",
        UpdateTargetId = "createClienteContainer",
        InsertionMode = InsertionMode.Replace
    }, new { @class = "form-horizontal", role = "form" }))

    {
        <div class="modal-body">

            <div class="col-lg-12">
                <div class="panel with-nav-tabs panel-primary">
                    <div class="panel-heading">
                        <ul class="nav nav-tabs">
                            <li class="active"><a href="#tab1primary">Generales</a></li>
                            <li><a href="#tab2primary">Direccion</a></li>
                            <li><a href="#tab3primary">Oficina y Contacto</a></li>
                            <li><a href="#tab4primary">Observaciones</a></li>
                            @*<li class="dropdown">
                                <a href="#">Dropdown <span class="caret"></span></a>
                                <ul class="dropdown-menu">
                                    <li><a href="#tab4primary">Primary 4</a></li>
                                    <li><a href="#tab5primary">Primary 5</a></li>
                                </ul>
                            </li>*@
                        </ul>
                    </div>
                    <div class="panel-body">
                        <div class="tab-content">
                            <div class="tab-pane fade in active" id="tab1primary">
                                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

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

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

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

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

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

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

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

                                <div class="form-group">
                                    @Html.LabelFor(model => model.SEXO_Cliente, htmlAttributes: new { @class = "control-label col-md-2" })
                                    <div class="col-md-10">
                                        @Html.DropDownListFor(model => model.SEXO_Cliente, new SelectList(new[] { "F", "M" }), new { @class = "form-control" })
                                        @Html.ValidationMessageFor(model => model.SEXO_Cliente, "", new { @class = "text-danger" })
                                    </div>
                                </div>

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

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

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

                                <div class="form-group">
                                    @Html.LabelFor(model => model.EDO_Cliente, htmlAttributes: new { @class = "control-label col-md-2" })
                                    <div class="col-md-10">
                                        @*@Html.EditorFor(model => model.EDO_Cliente, new { htmlAttributes = new { @class = "form-control" } })*@
                                        @Html.DropDownListFor(model => model.EDO_Cliente, new SelectList(new[] { "Aguascalientes","Baja California","Baja California Sur","Campeche","Chiapas","Chihuahua","Ciudad de Mexico","Coahuila","Colima","Durango","Guanajuato",
                    "Guerrero","Hidalgo","Jalisco","México","Michoacán","Morelos","Nayarit","Nuevo León","Oaxaca","Puebla","Querétaro","Quintana Roo","San Luis Potosi","Sinaloa","Sonora",
                    "Tabasco","Tamaulipas","Tlaxcala","Veracruz","Yucatán","Zacatecas" }), new { @class = "form-control" })
                                        @Html.ValidationMessageFor(model => model.EDO_Cliente, "", new { @class = "text-danger" })
                                    </div>
                                </div>

                            </div>
                            <div class="tab-pane fade" id="tab3primary">

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

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

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

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

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

                            </div>
                            <div class="tab-pane fade" id="tab4primary">

                                <div class="form-group">
                                    @Html.LabelFor(model => model.Inactivo_Cliente, htmlAttributes: new { @class = "control-label col-md-3" })
                                    <div class="col-md-9">
                                        @Html.DropDownListFor(model => model.Inactivo_Cliente, new SelectList(new List<object> { new { value = 0, text = "Activo" }, new { value = 1, text = "Inactivo" } }, "value", "text", 2), new { @class = "form-control" })
                                        @Html.ValidationMessageFor(model => model.Inactivo_Cliente, "", new { @class = "text-danger" })
                                    
                                



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

                        
                    
                
            

       

            <div class="modal-footer">
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        Close
                        
                    </div>
                </div>
            </div>
        }
    




As I mention above the first time the DatePicker is working and I can see the calendar.

Once information is complete, I save the data using AJAX.BeginForm once the SUCCES is complete I call the function OnSuccess = "CreateClienteSuccess", This fucntion is on the Main View.

here is what I have on my controller to save the data



[HttpPost]
        public async Task<actionresult> Create(cliente newcliente)
        {
            if (!ModelState.IsValid)
                return View("_CreateClientePartial", newcliente);


            db.clientes.Add(newcliente);

            var task = db.SaveChangesAsync();
            await task;

            if (task.Exception != null)
            {
                ModelState.AddModelError("", "No se puede crear el cliente");
                return View("_CreateClientePartial", newcliente);
            }

            return Content("success");
        }


After information is save I return to my Main View.

The problem comes here If I try to add a new Client, this time the DatePicker is not showing the calendar.

After reading many cases here I understand is somethign about the DatePicker not being initialize again, I been trying many things but not luck.

Instead of put all the options I tried to make it worked, I rather just put the code that is workign fine and with your help find what I need.

BTW, I have on my _layout View all the scripts and css classes.

Thanks for your help.

What I have tried:

After reading many cases here I understand is somethign about the DatePicker not being initialize again, I been trying many things but not luck.

Instead of put all the options I tried to make it worked, I rather just put the code that is workign fine and with your help find what I need.</div></div></div></div></div></div></div></div></div></div>

1 Ответов

Рейтинг:
2

Sung Shing

инициализируйте свой выбор даты в частичном представлении.

поместите блок скрипта, как показано ниже, в конец вашего частичного представления. это должно сработать.

& lt;скрипт>
$(documement).ready (функция (e){
$("#FEC_NAC_Cliente"). datepicker({
формат даты: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
yearRange: "-100:+0"
});
}));
< / script>


Member 13044878

Привет, Сун Шинг.

Спасибо за вашу помощь, но все равно проблема. Datepicker открывается нормально в первый раз, во второй раз он не показывает, используя Chrome и F12, нет ошибок или чего-то такого, что может привести меня к ошибке. Есть какие-нибудь идеи?


Спасибо

Sung Shing

при создании элементов частичного представления вам нужно будет выполнить javascript, чтобы привязать datepicker к вновь созданному полю ввода. То есть вы должны поместить javascript в конец частичного представления рендеринга.

не меняя код, запустите этот javascript после того, как ваш datepicker не появился. вы поймете, что я имею в виду.

$("#FEC_NAC_Cliente"). datepicker({
формат даты: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
yearRange: "-100:+0"
});