locked
Create Forms modal RRS feed

  • Question

  • User-508988007 posted

    Hi,Good morning everyone, it is my first day in the forum. I am very excited because I know it will be of great help to me. I am also very new to mvc. I need to make a modal table with bootstrap in the form that contains a table I would like to have a list of employees and that when selecting a record and pressing a button close the modal and that record is loaded into an editorFor control, for this I have done all this, which of course must be very badly done

    @model InventarioWeb.Models.Modelo.usuario
    
    @{
        ViewBag.Title = "Create";
    }
    <div id="#mymodal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display:none">
        <div class="modal-dialog">
            <div class=" modal-content">
                <div class="modal-header">
                    <h4>Cabecera</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="modal-content">
                        Cargando...
                    </div>
    
                </div>
                <div class="modal-footer">
                    <button class="btn btn-success"> Guardar</button>
                </div>
            </div>
        </div>
    </div>
    <h2>Create</h2>
    
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <form class="container">
            <div class="form-horizontal">
                <h4>usuario</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group row">
                    @Html.LabelFor(model => model.empleadoId, "Empleado", htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-8">
                        @*@Html.DropDownList("empleadoId", null, htmlAttributes: new { @class = "form-control form-control-sm" })*@
                        @Html.EditorFor(model => model.empleadoId, new { htmlAttributes = new { @class = "form-control form-control-sm" } })
                        @Html.ValidationMessageFor(model => model.empleadoId, "", new { @class = "text-danger" })
                    </div>
                    <a id="btnnuevo"data-toggle="modal" href="#mymodal" class="btn btn-success">Empleado</a>
                </div>
                <div class="form-group row">
                    @Html.LabelFor(model => model.nombreUsuario, htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.nombreUsuario, new { htmlAttributes = new { @class = "form-control form-control-sm" } })
                        @Html.ValidationMessageFor(model => model.nombreUsuario, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group row">
                    @Html.LabelFor(model => model.contrasenha, htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.contrasenha, new { htmlAttributes = new { @class = "form-control form-control-sm" } })
                        @Html.ValidationMessageFor(model => model.contrasenha, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group row">
                    @Html.LabelFor(model => model.perfilId, "Perfil", htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownList("perfilId", null, htmlAttributes: new { @class = "form-control form-control-sm" })
                        @Html.ValidationMessageFor(model => model.perfilId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
    
    
                <div class="form-group row">
                    @Html.LabelFor(model => model.estadoId, "Estado", htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownList("estadoId", null, htmlAttributes: new { @class = "form-control form-control-sm" })
                        @Html.ValidationMessageFor(model => model.estadoId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10" style="text-align:right">
                        @*<input type="submit" value="Crear" class="btn btn-primary" />*@
                    </div>
                </div>
                <div class=" form-group">
                    <input type="text" id="name" value="aaaa" />
                </div>
            </div>
        </form>
    
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script>
    
    
        $('#btnnuevo').click(function(eve) {
            $("#modal-content").load("/empleadoes/ListaModal")
        
        });
    </script>
    

    Please could you help me with an example or an idea of ​​how to solve this problem

    Thank you

    RM.

    Sunday, August 30, 2020 3:50 PM

Answers

  • User1686398519 posted

    Hi Roberto0123456,

    1. change from view to partialview
      • A partial view is a reusable portion of a web page.The partial view is used for a small part of the content and can be reused on different pages or used multiple times in the page.
      • You can see that the partial view you created is called Table. When you do not set the name of the returned partial view, the default is the same as the name of the action. You can modify the code like this.
        • public ActionResult ListaModal()
          {
                 var empleado = db.empleado.Include(e => e.cargo).Include(e => e.extensionci);
                 return PartialView("Table",empleado.ToList());
          }
    2. @Scripts does not exist in the current context*@
      • You can check if System.Web.Optimization is added in ~/Views/web.config.
        • <namespaces>
             <add namespace="System.Web.Mvc" />
             <add namespace="System.Web.Mvc.Ajax" />
             <add namespace="System.Web.Mvc.Html" />
             <add namespace="System.Web.Optimization"/>
             <add namespace="System.Web.Routing" />
             <add namespace="DailyMVCDemo" />
          </namespaces>
    3. @Scripts.Render("~/bundles/jquery")@* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@ @Scripts.Render("~/Scripts/jquery.validate.min.js") @* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@ @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js") @* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@ @Scripts.Render("~/bundles/bootstrap") @* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@ @RenderSection("scripts", required: false)
      <script src="~/Scripts/bootstrap.min.js"></script>
      <script src="~/Scripts/jquery-3.4.1.min.js"></script>
      <script src="~/Scripts/jquery.validate.min.js"></script>
      <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
      • In the _Layout view, the files are repeatedly referenced in these two places.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 3, 2020 3:21 AM

All replies

  • User1686398519 posted

    Hi Roberto0123456,

    According to your needs, I made an example based on your code.

    1. The example does not use a database, you can modify it according to your needs.
    2. <div id="#mymodal"
      • In the example, I changed "#mymodal" to "mymodal".
    3. For more detailed modifications, you can refer to the following example, and the key points are marked with colors.

    Note: You can check this link to start using ASP.NET MVC 5.

    Model

        public class usuario
        {
            public int empleadoId { get; set; }
            public string nombreUsuario { get; set; }
            public string contrasenha { get; set; }
            public int perfilId { get; set; }
            public int estadoId { get; set; }
    //The NotMapped attribute can be applied to properties of an entity class for which we do not want to create corresponding columns in the database [NotMapped] public SelectList perfilIdselectlist { get; set; } [NotMapped] public SelectList estadoIdselectlist { get; set; } }

    Controller

            public ActionResult Create()
            {
                ViewBag.perfilIdselectlist = perfilIdselectlist(); 
                ViewBag.estadoIdselectlist = estadoIdselectlist(); //set data to display the drop-down list
                return View();
            }
            public ActionResult usuarioList()
            {
                //To simplify the test, some data are assumed
                //You can use the database to persist data
                return PartialView(testlist());//Pass data to PartialView named usuarioList
            }
            //Suppose some usuario data is used to display in the modal
            public List<usuario> testlist()
            {
                List<usuario> testlist = new List<usuario>();
                for (int i = 1; i < 8; i++)
                {
                    testlist.Add(new usuario
                    {
                        empleadoId = i,
                        nombreUsuario = "nombreUsuario" + i.ToString(),
                        contrasenha = "contrasenha" + i.ToString(),
                        perfilId = i > 3 ? 2 : 1,
                        estadoId = i > 3 ? 3 : 2,
                        perfilIdselectlist = new SelectList(perfilIdselectlist(), "Value", "Text"),
                        estadoIdselectlist = new SelectList(estadoIdselectlist(), "Value", "Text")
    
                    });
                }
                return testlist;
            }
            //Suppose some estadoId data is used to display the drop-down list
            public List<SelectListItem> estadoIdselectlist()
            {
                List<SelectListItem> estadoIdselectlist = new List<SelectListItem>();
                for (int i = 1; i < 4; i++)
                {
                    SelectListItem item = new SelectListItem()
                    {
                        Value = i.ToString(),
                        Text = "estadoId" + i.ToString()
    
                    };
                    estadoIdselectlist.Add(item);
                }
                return estadoIdselectlist;
            }
            //Suppose some perfilId data is used to display the drop-down list
            public List<SelectListItem> perfilIdselectlist()
            {
                List<SelectListItem> perfilIdselectlist = new List<SelectListItem>();
                for (int i = 1; i < 4; i++)
                {
                    SelectListItem item = new SelectListItem()
                    {
                        Value = i.ToString(),
                        Text = "perfilId" + i.ToString()
    
                    };
                    perfilIdselectlist.Add(item);
                }
                return perfilIdselectlist;
            }

    Create.cshtml

    @model WebApplication26.Models.usuario
    @{
        ViewBag.Title = "Create";
    }
    <div id="mymodal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display:none">
        <div class="modal-dialog">
            <div class=" modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4>Cabecera</h4>
                </div>
                <div class="modal-body">
                    <div id="modal-content">
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="addTest" class="btn btn-success"> Guardar</button>
                </div>
            </div>
        </div>
    </div>
    <h2>Create</h2>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <form class="container">
            <div class="form-horizontal">
                <h4>usuario</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group row">
                    @Html.LabelFor(model => model.empleadoId, "Empleado", htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-8">
                        @Html.TextBoxFor(model => model.empleadoId, new { @class = "form-control form-control-sm" })
                        @Html.ValidationMessageFor(model => model.empleadoId, "", new { @class = "text-danger" })
                    </div>
                    <button type="button" id="btnnuevo" class="btn btn-success">Empleado</button>
                </div>
                <div class="form-group row">
                    @Html.LabelFor(model => model.nombreUsuario, htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(model => model.nombreUsuario, new { @class = "form-control form-control-sm" })
                        @Html.ValidationMessageFor(model => model.nombreUsuario, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group row">
                    @Html.LabelFor(model => model.contrasenha, htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(model => model.contrasenha, new { @class = "form-control form-control-sm" })
                        @Html.ValidationMessageFor(model => model.contrasenha, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group row">
                    @Html.LabelFor(model => model.perfilId, "Perfil", htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownListFor(model => model.perfilId, new SelectList(ViewBag.perfilIdselectlist, "Value", "Text"), "Please Select", htmlAttributes: new { @class = "form-control form-control-sm" })
                        @Html.ValidationMessageFor(model => model.perfilId, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group row">
                    @Html.LabelFor(model => model.estadoId, "Estado", htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownListFor(model => model.estadoId, new SelectList(ViewBag.estadoIdselectlist, "Value", "Text"), "Please Select", htmlAttributes: new { @class = "form-control form-control-sm" })
                        @Html.ValidationMessageFor(model => model.estadoId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10" style="text-align:right">
                        @*<input type="submit" value="Crear" class="btn btn-primary" />*@
                    </div>
                </div>
                <div class=" form-group">
                    <input type="text" id="name" value="aaaa" />
                </div>
            </div>
        </form>
    }
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    @*Why put the js code in section scripts{}: 
        Because the view uses the u_Layout view, at the same time there is 
        @RenderSection("scripts", required: false) on the u_Layout view
    *@
    @section scripts{
        <script src="~/Scripts/jquery.validate.min.js"></script>
        <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
        <script>
            $('#btnnuevo').click(function () {
                $("#modal-content").load("@Url.Action("usuarioList")");
                $("#mymodal").modal("show");
            });
        </script>
    }

    usuarioList.cshtml

    @model IEnumerable<WebApplication26.Models.usuario>
    <table id="usuarioListTable" class="table table-bordered table-striped">
        <thead>
            <tr>
                <td>@Html.DisplayNameFor(m => m.empleadoId)</td>
                <td>@Html.DisplayNameFor(m => m.nombreUsuario)</td>
                <td>@Html.DisplayNameFor(m => m.contrasenha)</td>
                <td>@Html.DisplayNameFor(m => m.perfilId)</td>
                <td>@Html.DisplayNameFor(m => m.empleadoId)</td>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr class="test">
                    <td>@Html.DisplayFor(m => item.empleadoId)</td>
                    <td>@Html.DisplayFor(m => item.nombreUsuario)</td>
                    <td>@Html.DisplayFor(m => item.contrasenha)</td>
                    <td>
                        @*new SelectList(item.perfilIdselectlist, "Value", "Text", item.perfilId)
                          The fourth parameter determines which is selected
                        *@
                        @Html.DropDownListFor(m => item.perfilId, new SelectList(item.perfilIdselectlist, "Value", "Text", item.perfilId), "Please Select")
                    </td>
                    <td>
                        @Html.DropDownListFor(m => item.empleadoId, new SelectList(item.estadoIdselectlist, "Value", "Text", item.estadoId), "Please Select")
                    </td>
                </tr>
            }
        </tbody>
    </table>
    <script>
        //When a row in the table is clicked
        $('#usuarioListTable').on('click', '.test', function (event) {
            var currenttd = $(this).find("td");
            $(this).addClass('success').siblings().removeClass('success');
            $(this).addClass('active').siblings().removeClass('active');
            $('#addTest').click(function () {
                $("#empleadoId").val(currenttd.eq(0).html());
                $("#nombreUsuario").val(currenttd.eq(1).html());
                $("#contrasenha").val(currenttd.eq(2).html());
                $('#perfilId').find('option[value=' + currenttd.eq(3).find("option:selected").val() + ']').attr('selected', 'selected');
                $('#estadoId').find('option[value=' + currenttd.eq(4).find("option:selected").val() + ']').attr('selected', 'selected');
                $("#mymodal").modal("hide");//hide modal
            });
        });
    </script>

    Here is the result.

    Best Regards,

    YihuiSun

    Monday, August 31, 2020 5:48 AM
  • User-508988007 posted

    Thank you very much, it is just what I needed. excellent contribution, I know it will also serve other people

    Roberto

    Tuesday, September 1, 2020 12:26 AM
  • User-508988007 posted

    YihuiSun, 
    for my lack of experience copy and paste change
    $ ("# modal-content"). load ("@ Url.Action (" userList ")"); for this code, $ ("# modal-content"). load ("@ Url.Action (" ListModal ")");
    but it doesn't show anything in my create, so it doesn't load the form

    This is my code

    @model InventarioWeb.Models.Modelo.usuario
    
    @{
        ViewBag.Title = "Create";
    }
    <!-- Button trigger modal -->
    <div id="mymodal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display:none">
        <div class="modal-dialog">
            <div class=" modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4>Cabecera</h4>
                </div>
                <div class="modal-body">
                    <div id="modal-content">
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="addTest" class="btn btn-success"> Guardar</button>
                </div>
            </div>
        </div>
    </div>
    <h2>Create</h2>
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <form class="container">
            <div class="form-horizontal">
                <h4>usuario</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group row">
                    @Html.LabelFor(model => model.empleadoId, "Empleado", htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.empleadoId, new { htmlAttributes = new { @class = "form-control form-control-sm" } })
                        @Html.ValidationMessageFor(model => model.empleadoId, "", new { @class = "text-danger" })
                    </div>
                    <button type="button" id="btnnuevo" class="btn btn-success">Empleado</button>
                </div>
                <div class="form-group row">
                    @Html.LabelFor(model => model.nombreUsuario, htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.nombreUsuario, new { htmlAttributes = new { @class = "form-control form-control-sm" } })
                        @Html.ValidationMessageFor(model => model.nombreUsuario, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group row">
                    @Html.LabelFor(model => model.contrasenha, htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.contrasenha, new { htmlAttributes = new { @class = "form-control form-control-sm" } })
                        @Html.ValidationMessageFor(model => model.contrasenha, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group row">
                    @Html.LabelFor(model => model.perfilId, "Perfil", htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownList("perfilId", null, htmlAttributes: new { @class = "form-control form-control-sm" })
                        @Html.ValidationMessageFor(model => model.perfilId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
    
    
                <div class="form-group row">
                    @Html.LabelFor(model => model.estadoId, "Estado", htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownList("estadoId", null, htmlAttributes: new { @class = "form-control form-control-sm" })
                        @Html.ValidationMessageFor(model => model.estadoId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10" style="text-align:right">
                    </div>
                </div>
                <div class=" form-group">
                    <input type="text" id="name" value="aaaa" />
                </div>
            </div>
        </form>
    
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    
        <script src="~/Scripts/jquery.validate.min.js"></script>
        <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
        <script>
            $('#btnnuevo').click(function () {
                alert("Testing if the button works")
                $("#modal-content").load("@Url.Action("ListaModal")");
                $("#mymodal").modal("show");
            });
        </script>
    
    
    
    

    The table is this

    @model IEnumerable<InventarioWeb.Models.Modelo.empleado>
        @*@{
            
        }
    
    
        <h4>holas</h4>*@
    @*@model IEnumerable<WebApplication26.Models.usuario>*@
    <table id="usuarioListTable" class="table table-bordered table-striped">
        <thead>
            <tr>
                <td>@Html.DisplayNameFor(m => m.apellidoMaterno)</td>
                <td>@Html.DisplayNameFor(m => m.apellidoPaterno)</td>
                <td>@Html.DisplayNameFor(m => m.primerNombre)</td>
                <td>@Html.DisplayNameFor(m => m.segundoNombre)</td>
    
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
            <tr class="test">
                <td>@Html.DisplayFor(m => item.apellidoMaterno)</td>
                <td>@Html.DisplayFor(m => item.apellidoPaterno)</td>
                <td>@Html.DisplayFor(m => item.primerNombre)</td>
                <td>@Html.DisplayFor(m => item.segundoNombre)</td>
                @*<td>
    
                    @Html.DropDownListFor(m => item.perfilId, new SelectList(item.perfilIdselectlist, "Value", "Text", item.perfilId), "Please Select")
                </td>
                <td>
                    @Html.DropDownListFor(m => item.empleadoId, new SelectList(item.estadoIdselectlist, "Value", "Text", item.estadoId), "Please Select")
                </td>*@
            </tr>
            }
        </tbody>
    </table>
    <script>
        //When a row in the table is clicked
        $('#usuarioListTable').on('click', '.test', function (event) {
            var currenttd = $(this).find("td");
            $(this).addClass('success').siblings().removeClass('success');
            $(this).addClass('active').siblings().removeClass('active');
            $('#addTest').click(function () {
                $("#empleadoId").val(currenttd.eq(0).html());
                $("#nombreUsuario").val(currenttd.eq(1).html());
                $("#contrasenha").val(currenttd.eq(2).html());
                $('#perfilId').find('option[value=' + currenttd.eq(3).find("option:selected").val() + ']').attr('selected', 'selected');
                $('#estadoId').find('option[value=' + currenttd.eq(4).find("option:selected").val() + ']').attr('selected', 'selected');
                $("#mymodal").modal("hide");//hide modal
            });
        });
    </script>
    
    
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using InventarioWeb.Models.Modelo;
    
    namespace InventarioWeb.Controllers
    {
        public class empleadoesController : Controller
        {
            private inventarioEntities db = new inventarioEntities();
    
            // GET: empleadoes
                public ActionResult Index()
            {
                var empleado = db.empleado.Include(e => e.cargo).Include(e => e.extensionci);
                return View(empleado.ToList());
            }
    
            // GET: empleadoes/Details/5
            public ActionResult Details(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                empleado empleado = db.empleado.Find(id);
                if (empleado == null)
                {
                    return HttpNotFound();
                }
                return View(empleado);
            }
    
            // GET: empleadoes/Create
            public ActionResult Create()
            {
                ViewBag.cargoId = new SelectList(db.cargo, "Id", "nombreCargo");
                ViewBag.entensionId = new SelectList(db.extensionci, "Id", "extendido");
                return View();
            }
    
            // POST: empleadoes/Create
            // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener 
            // más información vea https://go.microsoft.com/fwlink/?LinkId=317598.
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Create([Bind(Include = "Id,primerNombre,segundoNombre,apellidoPaterno,apellidoMaterno,carnetIdentidad,fechaIngreso,cargoId,entensionId")] empleado empleado)
            {
                if (ModelState.IsValid)
                {
                    db.empleado.Add(empleado);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                ViewBag.cargoId = new SelectList(db.cargo, "Id", "nombreCargo", empleado.cargoId);
                ViewBag.entensionId = new SelectList(db.extensionci, "Id", "extendido", empleado.entensionId);
                return View(empleado);
            }
    
            // GET: empleadoes/Edit/5
            public ActionResult Edit(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                empleado empleado = db.empleado.Find(id);
                if (empleado == null)
                {
                    return HttpNotFound();
                }
                ViewBag.cargoId = new SelectList(db.cargo, "Id", "nombreCargo", empleado.cargoId);
                ViewBag.entensionId = new SelectList(db.extensionci, "Id", "extendido", empleado.entensionId);
                return View(empleado);
            }
    
            // POST: empleadoes/Edit/5
            // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener 
            // más información vea https://go.microsoft.com/fwlink/?LinkId=317598.
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Edit([Bind(Include = "Id,primerNombre,segundoNombre,apellidoPaterno,apellidoMaterno,carnetIdentidad,fechaIngreso,cargoId,entensionId")] empleado empleado)
            {
                if (ModelState.IsValid)
                {
                    db.Entry(empleado).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                ViewBag.cargoId = new SelectList(db.cargo, "Id", "nombreCargo", empleado.cargoId);
                ViewBag.entensionId = new SelectList(db.extensionci, "Id", "extendido", empleado.entensionId);
                return View(empleado);
            }
    
            // GET: empleadoes/Delete/5
            public ActionResult Delete(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                empleado empleado = db.empleado.Find(id);
                if (empleado == null)
                {
                    return HttpNotFound();
                }
                return View(empleado);
            }
    
            // POST: empleadoes/Delete/5
            [HttpPost, ActionName("Delete")]
            [ValidateAntiForgeryToken]
            public ActionResult DeleteConfirmed(int id)
            {
                empleado empleado = db.empleado.Find(id);
                db.empleado.Remove(empleado);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
            ///////////
            ///
            public ActionResult ListaModal()
            {
                var empleado = db.empleado.Include(e => e.cargo).Include(e => e.extensionci);
                return View(empleado.ToList());
            }
        }
    }
    Also try this code $ ("# modal-content"). load ("@ Url.Action (" ~ Employees / ListModal ")");




    Please one more help,

    thank you very much

    Roberto

    Tuesday, September 1, 2020 1:32 AM
  • User1686398519 posted

    Hi Roberto0123456,

    I checked the code you provided, and you did not reference the jquery file.

    1. You can check the Console via F12 in the browser to see if there is an error message similar to "Uncaught ReferenceError: jQuery is not defined".
    2. If this error occurs, the error is caused by the lack of jquery file, which means that your modal cannot be displayed.
    3. You seem to be wondering why there is no code that references the jquery file in my example.
      • Because the view I provided uses the _Layout view, jquery has already referenced the jquery file in the _Layout view.
      • At the same time, there is @RenderSection("scripts", required: false) on the _Layout view, so for pages that use the _Layout view, just put js in @section scripts{}. According to the code you provided, you also use the _Layout view.I have also explained it by adding comments to the example, you can check the previous example.
        • Create.cshtml
          • @section scripts{
                <script src="~/Scripts/jquery.validate.min.js"></script>
                <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
                <script>
                    $('#btnnuevo').click(function () {
                        $("#modal-content").load("@Url.Action("usuarioList")");
                        $("#mymodal").modal("show");
                    });
                </script>
            }
        •  _Layout
          •     @Scripts.Render("~/bundles/jquery")* The jquery file has been referenced here *@
                @Scripts.Render("~/Scripts/jquery.validate.min.js")
                @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
                @Scripts.Render("~/bundles/bootstrap")
                @RenderSection("scripts", required: false)
      • If you do not reference the _Layout view, then you can also directly reference the jquery file.
        • <script src="~/Scripts/jquery-3.4.1.min.js"></script>
          <script src="~/Scripts/jquery.validate.min.js"></script>
          <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
          <script>
                  $('#btnnuevo').click(function () {
                      $("#modal-content").load("@Url.Action("usuarioList")");
                      $("#mymodal").modal("show");
                  });
          </script>
          
          

    Note: If you are interested, you can check the links below so that you can better understand the points I mentioned above.

    1. What is Layout View in ASP.NET MVC
    2. Bundling and Minification

    Best Regards,

    YihuiSun

    Tuesday, September 1, 2020 10:00 AM
  • User-508988007 posted

    Hi YihuiSun

    Good night, yesterday I did not respond to your message because I was trying to sort my code, since I had many comments, now I have, I think, all the basics. but when I apply the example that happens to me in the same way, I can't, and I'm sure that the problem is not in the code that you send me, but rather in how I add it to my project.

    I pass my code again in order
    controller layout
    user view.
    and the modal table

    So please tell me where exactly I should put my code

    It is also worth mentioning that you change from view to partialview in the controller in the method

    public ActionResult ListaModal()
    {
    var empleado = db.empleado.Include(e => e.cargo).Include(e => e.extensionci);
    //return View(empleado.ToList()); @* change View to PartialView*@
    return PartialView(empleado.ToList());
    }

    Since I saw that in code that you. send me there is this line

    Return partialview(..)

    in advance I apologize for the inconvenience, and thank you for the collaboration
    I send the code

    controller

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using InventarioWeb.Models.Modelo;
    
    namespace InventarioWeb.Controllers
    {
        public class empleadoesController : Controller
        {
            private inventarioEntities db = new inventarioEntities();
    
            // GET: empleadoes
                public ActionResult Index()
            {
                var empleado = db.empleado.Include(e => e.cargo).Include(e => e.extensionci);
                return View(empleado.ToList());
            }
    
            // GET: empleadoes/Details/5
            public ActionResult Details(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                empleado empleado = db.empleado.Find(id);
                if (empleado == null)
                {
                    return HttpNotFound();
                }
                return View(empleado);
            }
    
            // GET: empleadoes/Create
            public ActionResult Create()
            {
                ViewBag.cargoId = new SelectList(db.cargo, "Id", "nombreCargo");
                ViewBag.entensionId = new SelectList(db.extensionci, "Id", "extendido");
                return View();
            }
    
            // POST: empleadoes/Create
            // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener 
            // más información vea https://go.microsoft.com/fwlink/?LinkId=317598.
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Create([Bind(Include = "Id,primerNombre,segundoNombre,apellidoPaterno,apellidoMaterno,carnetIdentidad,fechaIngreso,cargoId,entensionId")] empleado empleado)
            {
                if (ModelState.IsValid)
                {
                    db.empleado.Add(empleado);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                ViewBag.cargoId = new SelectList(db.cargo, "Id", "nombreCargo", empleado.cargoId);
                ViewBag.entensionId = new SelectList(db.extensionci, "Id", "extendido", empleado.entensionId);
                return View(empleado);
            }
    
            // GET: empleadoes/Edit/5
            public ActionResult Edit(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                empleado empleado = db.empleado.Find(id);
                if (empleado == null)
                {
                    return HttpNotFound();
                }
                ViewBag.cargoId = new SelectList(db.cargo, "Id", "nombreCargo", empleado.cargoId);
                ViewBag.entensionId = new SelectList(db.extensionci, "Id", "extendido", empleado.entensionId);
                return View(empleado);
            }
    
            // POST: empleadoes/Edit/5
            // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener 
            // más información vea https://go.microsoft.com/fwlink/?LinkId=317598.
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Edit([Bind(Include = "Id,primerNombre,segundoNombre,apellidoPaterno,apellidoMaterno,carnetIdentidad,fechaIngreso,cargoId,entensionId")] empleado empleado)
            {
                if (ModelState.IsValid)
                {
                    db.Entry(empleado).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                ViewBag.cargoId = new SelectList(db.cargo, "Id", "nombreCargo", empleado.cargoId);
                ViewBag.entensionId = new SelectList(db.extensionci, "Id", "extendido", empleado.entensionId);
                return View(empleado);
            }
    
            // GET: empleadoes/Delete/5
            public ActionResult Delete(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                empleado empleado = db.empleado.Find(id);
                if (empleado == null)
                {
                    return HttpNotFound();
                }
                return View(empleado);
            }
    
            // POST: empleadoes/Delete/5
            [HttpPost, ActionName("Delete")]
            [ValidateAntiForgeryToken]
            public ActionResult DeleteConfirmed(int id)
            {
                empleado empleado = db.empleado.Find(id);
                db.empleado.Remove(empleado);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
            ///////////
            ///
            public ActionResult ListaModal()
            {
                var empleado = db.empleado.Include(e => e.cargo).Include(e => e.extensionci);
                //return View(empleado.ToList()); @* change View to PartialView*@
                return PartialView(empleado.ToList());
            }
        }
    }
    

    Layout.cshtml

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link href="https://fonts.googleapis.com/css2?family=Concert+One&display=swap" rel="stylesheet">
        <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
        <title>@ViewBag.Title  </title>
        <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
        <link href="~/Content/bootstrap-grid.min.css" rel="stylesheet" />
        <link href="~/Content/estilos.css" rel="stylesheet" />
    </head>
    <body>
        <div class="sidebar">
            <h2> MENU</h2>
            <ul>
                <li>@Html.ActionLink("Crear Cargo", "Create", "cargoes")</li>
                <li>@Html.ActionLink("Crear Empleado", "Create", "empleadoes")</li>
                <li>@Html.ActionLink("Crear Extension", "Create", "extensioncis")</li>
                <li>@Html.ActionLink("Crear Estado", "Create", "estados")</li>
                <li>@Html.ActionLink("Crear Moneda", "Create", "monedas")</li>
                <li>@Html.ActionLink("Unidad Med.", "Create", "unidadmedidas")</li>
                <li>@Html.ActionLink("Tipo Iva", "Create", "tipoIvas")</li>
                <li>@Html.ActionLink("Crear Perfil", "Create", "perfiles")</li>
                <li>@Html.ActionLink("Crear Usuario", "Create", "usuarios")</li>
                <li>@Html.ActionLink("Crear Producto", "Create", "productos")</li>
                <li><a href="">Consultas</a></li>
                <li><a href="">Salir</a></li>
            </ul>
    
        </div>
    
        <div class="contenido">
            <img src="Lista.png" alt="" class="menu-bar">
            @RenderBody()
        </div>
        @Scripts.Render("~/bundles/jquery")@* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@
        @Scripts.Render("~/Scripts/jquery.validate.min.js") @* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@
        @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js") @* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@
        @Scripts.Render("~/bundles/bootstrap")  @* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@
        @RenderSection("scripts", required: false)
    
    
        @*If you do not reference the _Layout view, then you can also directly reference the jquery file.*@
    
        <script src="~/Scripts/bootstrap.min.js"></script>
        <script src="~/Scripts/jquery-3.4.1.min.js"></script>
        <script src="~/Scripts/jquery.validate.min.js"></script>
        <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
        <script>
            $('#btnnuevo').click(function () {
                $("#modal-content").load("@Url.Action("ListaModal")");@* change userList to ListModal*@
                $("#mymodal").modal("show");
            });
        </script>
    </body>
    
    </html>
    

    Create

    @model InventarioWeb.Models.Modelo.usuario
    
    @{
        ViewBag.Title = "Create";
    }
    <!-- Button trigger modal -->
    <div id="mymodal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display:none">
        <div class="modal-dialog">
            <div class=" modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4>Cabecera</h4>
                </div>
                <div class="modal-body">
                    <div id="modal-content">
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="addTest" class="btn btn-success"> Guardar</button>
                </div>
            </div>
        </div>
    </div>
    <h2>Create</h2>
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <form class="container">
            <div class="form-horizontal">
                <h4>usuario</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group row">
                    @Html.LabelFor(model => model.empleadoId, "Empleado", htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.empleadoId, new { htmlAttributes = new { @class = "form-control form-control-sm" } })
                        @Html.ValidationMessageFor(model => model.empleadoId, "", new { @class = "text-danger" })
                    </div>
                    <button type="button" id="btnnuevo" class="btn btn-success">Empleado</button>
                </div>
                <div class="form-group row">
                    @Html.LabelFor(model => model.nombreUsuario, htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.nombreUsuario, new { htmlAttributes = new { @class = "form-control form-control-sm" } })
                        @Html.ValidationMessageFor(model => model.nombreUsuario, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group row">
                    @Html.LabelFor(model => model.contrasenha, htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.contrasenha, new { htmlAttributes = new { @class = "form-control form-control-sm" } })
                        @Html.ValidationMessageFor(model => model.contrasenha, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group row">
                    @Html.LabelFor(model => model.perfilId, "Perfil", htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownList("perfilId", null, htmlAttributes: new { @class = "form-control form-control-sm" })
                        @Html.ValidationMessageFor(model => model.perfilId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
    
    
                <div class="form-group row">
                    @Html.LabelFor(model => model.estadoId, "Estado", htmlAttributes: new { @class = "col-form-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownList("estadoId", null, htmlAttributes: new { @class = "form-control form-control-sm" })
                        @Html.ValidationMessageFor(model => model.estadoId, "", new { @class = "text-danger" })
                    </div>
                </div>
    
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10" style="text-align:right">
                    </div>
                </div>
    
            </div>
        </form>
    
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    @section scripts{
        <script src="~/Scripts/jquery.validate.min.js"></script>
        <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
        <script>
            $('#btnnuevo').click(function () {
                $("#modal-content").load("@Url.Action("ListaModal")"); @* change userList to ListModal *@
                $("#mymodal").modal("show");
            });
        </script>
    }
    
    
    

    Table

    @model IEnumerable<InventarioWeb.Models.Modelo.empleado>
        @*@{
            
        }
    
    
        <h4>holas</h4>*@
    @*@model IEnumerable<WebApplication26.Models.usuario>*@
    <table id="usuarioListTable" class="table table-bordered table-striped">
        <thead>
            <tr>
                <td>@Html.DisplayNameFor(m => m.apellidoMaterno)</td>
                <td>@Html.DisplayNameFor(m => m.apellidoPaterno)</td>
                <td>@Html.DisplayNameFor(m => m.primerNombre)</td>
                <td>@Html.DisplayNameFor(m => m.segundoNombre)</td>
    
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
            <tr class="test">
                <td>@Html.DisplayFor(m => item.apellidoMaterno)</td>
                <td>@Html.DisplayFor(m => item.apellidoPaterno)</td>
                <td>@Html.DisplayFor(m => item.primerNombre)</td>
                <td>@Html.DisplayFor(m => item.segundoNombre)</td>
                @*<td>
    
                    @Html.DropDownListFor(m => item.perfilId, new SelectList(item.perfilIdselectlist, "Value", "Text", item.perfilId), "Please Select")
                </td>
                <td>
                    @Html.DropDownListFor(m => item.empleadoId, new SelectList(item.estadoIdselectlist, "Value", "Text", item.estadoId), "Please Select")
                </td>*@
            </tr>
            }
        </tbody>
    </table>
    <script>
        //When a row in the table is clicked
        //$('#usuarioListTable').on('click', '.test', function (event) {
        //    var currenttd = $(this).find("td");
        //    $(this).addClass('success').siblings().removeClass('success');
        //    $(this).addClass('active').siblings().removeClass('active');
        //    $('#addTest').click(function () {
        //        $("#empleadoId").val(currenttd.eq(0).html());
        //        $("#nombreUsuario").val(currenttd.eq(1).html());
        //        $("#contrasenha").val(currenttd.eq(2).html());
        //        $('#perfilId').find('option[value=' + currenttd.eq(3).find("option:selected").val() + ']').attr('selected', 'selected');
        //        $('#estadoId').find('option[value=' + currenttd.eq(4).find("option:selected").val() + ']').attr('selected', 'selected');
        //        $("#mymodal").modal("hide");//hide modal
        //    });
        //});
    </script>
    
    

    now I get this error message

    Server error in application '/'.
    Compilation error
    Description: An error occurred during the compilation of a resource required to service this request. Review the specific error details below and modify the source code accordingly.

    Compiler error message: CS0103: The name 'Scripts' does not exist in the current context

    Source code error:

    Please one more help
    Thank you

    Línea 36:         @RenderBody()
    Línea 37:     </div>
    Línea 38:     @Scripts.Render("~/bundles/jquery")@* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@
    Línea 39:     @Scripts.Render("~/Scripts/jquery.validate.min.js") @* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@
    Línea 40:     @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js") @* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@

    also this code appears
    Server error in application '/'.
    The following sections have been defined, but not submitted for the layout page "~ / Views / Shared / _Layout.cshtml": "scripts".

    Thursday, September 3, 2020 12:45 AM
  • User1686398519 posted

    Hi Roberto0123456,

    1. change from view to partialview
      • A partial view is a reusable portion of a web page.The partial view is used for a small part of the content and can be reused on different pages or used multiple times in the page.
      • You can see that the partial view you created is called Table. When you do not set the name of the returned partial view, the default is the same as the name of the action. You can modify the code like this.
        • public ActionResult ListaModal()
          {
                 var empleado = db.empleado.Include(e => e.cargo).Include(e => e.extensionci);
                 return PartialView("Table",empleado.ToList());
          }
    2. @Scripts does not exist in the current context*@
      • You can check if System.Web.Optimization is added in ~/Views/web.config.
        • <namespaces>
             <add namespace="System.Web.Mvc" />
             <add namespace="System.Web.Mvc.Ajax" />
             <add namespace="System.Web.Mvc.Html" />
             <add namespace="System.Web.Optimization"/>
             <add namespace="System.Web.Routing" />
             <add namespace="DailyMVCDemo" />
          </namespaces>
    3. @Scripts.Render("~/bundles/jquery")@* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@ @Scripts.Render("~/Scripts/jquery.validate.min.js") @* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@ @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js") @* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@ @Scripts.Render("~/bundles/bootstrap") @* this part @Scripts is underlined with a message that says the name @Scripts does not exist in the current context*@ @RenderSection("scripts", required: false)
      <script src="~/Scripts/bootstrap.min.js"></script>
      <script src="~/Scripts/jquery-3.4.1.min.js"></script>
      <script src="~/Scripts/jquery.validate.min.js"></script>
      <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
      • In the _Layout view, the files are repeatedly referenced in these two places.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 3, 2020 3:21 AM
  • User-508988007 posted

    Thank you very much, now if I look very good, thanks for the time invested in helping me, blessings

    RM.

    Friday, September 4, 2020 12:18 AM