简体   繁体   中英

JQuery not working in PartialView inside modal dialog

I'm trying to create a "Create" form as a modal dialog when the user clicks the create button. The Modal displays the partialview that contains the form. But when the user selects a value in the dropdownlist it should us AJAX to populate other information on the form. But the jquery call to lookupVendor information doesn't fire. I know i'm missing something, but just can't see it.. So any help would be great.

Controller

public ActionResult LookupVendor(int? id)
        {
            string VendorContact = "";
            string VendorPartNumber = "";
            decimal VendorPrice = 0;

            if (id != null)
            {
                var vendors = (from v in dbVendor.vendors where v.idVendor == id select v).ToList();
                var tmpnumber = (from x in dbVendor.vendorpartinformations where x.IDVendor == id && x.IDParts == id select x).ToList();

                foreach (var item in vendors)
                {
                    VendorContact = item.Contact;
                    
                }

                if (tmpnumber.Count != 0)
                {

                    foreach (var item1 in tmpnumber)
                    {
                        VendorPartNumber = item1.VendorPartNumber;
                        VendorPrice = (decimal)item1.VentorPrice;
                    }
                }
                else
                {
                    VendorPartNumber = "Not available from this Vendor";
                }
            }


            return Json(new { VendorContact = VendorContact, VendorPartNumber = VendorPartNumber, VendorPrice = VendorPrice }, JsonRequestBehavior.AllowGet);
        }

        
        public ActionResult Create(int? id, int? idVendor, int? idReference, int? Required,  RequisitionOrder model)
        {
            foreach (var Vendor in dbVendor.vendors)
            {
                model.VendorNames.Add(new SelectListItem { Text = Vendor.Name, Value = Vendor.idVendor.ToString() });
            }

            var Tmpdetails = dbParts.parts.Where(x => x.idParts == id).ToList();

            foreach(var item2 in Tmpdetails)
            {
                model.PartNumber = item2.PartNumber;
                model.PartDescription = item2.PartDescription;
                model.StockQTY = (int)item2.PartQTY;
                if(Required != null)
                {
                    model.RequisitionQTY = (int)Required;
                }
                else
                {
                    model.RequisitionQTY = (int)model.RequisitionQTY;
                }

                foreach(var item3 in dbPartType.parttypes)
                {
                    if(item3.idPartType == item2.PartType)
                    {
                        model.PartType = item3.PartType1;
                    }
                }
            }

            
            return PartialView("Create", model);
        }

Main Form

@model MYSQL___Parts_Management.Models.ItemsToOrder

@{
    ViewBag.Title = "ItemsToOrder";
}

<style>
    table, th, td {
        border: 0px solid black;
        padding: 5px;
        /*font-size: 12px;*/
    }

        table.center {
            margin-left: auto;
            margin-right: auto;
        }

    table {
        border-spacing: 15px;
    }

    .foo {
        color: red;
    }

    .modal-dialog {
        position: relative;
        display: table; /* <-- This makes the trick */
        overflow-y: auto;
        overflow-x: auto;
        width: auto;
        min-width: 300px;
    }
</style>
<br />
<br />

@using (Html.BeginForm("ItemToOrder", "PartRequisitions", FormMethod.Post))
{
    @Html.AntiForgeryToken()

<table style="filter: alpha(opacity=40); opacity: 0.95;border:2px black solid;width:100%" ;table-layout:fixed;>
    <tr>
        <th colspan="9" bgcolor="#dddddd" cellspacing="1" cellpadding="6" style="font-size: 15px;border:1px black solid;padding-left:0.8ex">Parts Order</th>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>

    <tr>
        <th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Part Description</th>
        <th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Part Number</th>
        <th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Minimum QTY</th>
        <th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Maximum QTY</th>
        <th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Stocked QTY</th>
        <th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Requested QTY</th>
        <th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Required QTY</th>
        <th></th>
        <th></th>
    </tr>
    @if (Model.Results.Count > 0)
    {
        foreach (var item in Model.Results)
        {

            <tr style="font-size:12px; font-weight: bold">
                @if (item.QTYDifference != 0)
                {
                    <td width="230" nowrap>
                        @Html.DisplayFor(modelItem => item.PartDescription) @Html.DisplayFor(modelItem => item.idParts)
                    </td>
                    <td nowrap align="center">
                        @Html.DisplayFor(modelItem => item.PartNumber)
                    </td>
                    <td nowrap align="center">
                        @Html.DisplayFor(modelItem => item.PartMinQTY)
                    </td>
                    <td align="center">
                        @Html.DisplayFor(modelItem => item.PartMaxQTY)
                    </td>
                    <td align="center">
                        @Html.DisplayFor(modelItem => item.PartQTY)
                    </td>
                    <td align="center">
                        @Html.DisplayFor(modelItem => item.RequestedQTY)
                    </td>
                    <td align="center">
                        @Html.DisplayFor(modelItem => item.QTYDifference)
                    </td>
                    <td> @Html.ActionLink(" ", "Create", "PartRequisitions", new { @id = item.idParts, @Required = item.QTYDifference }, new { @class = "glyphicon glyphicon-list-alt", @title = "Create PO", @data_modal = "" })</td>
                    <td></td>
                }
            </tr>
        }
    }
    <tr>
        <td colspan="9"></td>
    </tr>

</table>



}


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


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/scripts/appjs/PRequisitionIndex.js")

    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
}

Main Form - Script file

$(document).ready(function () {
    $(window).keydown(function (event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            return false;
        }
    });
});

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


});

function bindForm(dialog) {
    $('form', dialog).submit(function () {

        $('#progress').show();
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    $('#myModal').modal('hide');
                    $('#progress').hide();
                    window.location.href = "/PartRequisitions/ItemsToOrder";
                } else {
                    $('#progress').hide();
                    $('#myModalContent').html(result);
                    bindForm();
                }
            }
        });

        return false;
    });
}


        $(document).ready(function () {

            $('#data').after('<div id="nav"></div>');
            var rowsShown = 10;
            var rowsTotal = $('#data tbody tr').length;
            var numPages = rowsTotal / rowsShown;
            for (i = 0; i < numPages; i++) {
                var pageNum = i + 1;
                $('#nav').append('<a href="#" rel="' + i + '">' + pageNum + '</a> ');
            }
            $('#data tbody tr').hide();
            $('#data tbody tr').slice(0, rowsShown).show();
            $('#nav a:first').addClass('active');
            $('#nav a').bind('click', function () {

                $('#nav a').removeClass('active');
                $(this).addClass('active');
                var currPage = $(this).attr('rel');
                var startItem = currPage * rowsShown;
                var endItem = startItem + rowsShown;
                $('#data tbody tr').css('opacity', '0.0').hide().slice(startItem, endItem).
                    css('display', 'table-row').animate({ opacity: 1 }, 300);
            });
        });

Create Form as partial view

@model MYSQL___Parts_Management.Models.RequisitionOrder

@{
    ViewBag.Title = "Parts Requisition";
    Layout = "";
}

<style>
    table, th, td {
        border: 0px solid black;
        padding: 5px;
        /*font-size: 12px;*/
    }

        table.center {
            margin-left: auto;
            margin-right: auto;
        }

    table {
        border-spacing: 15px;
    }
</style>

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>

@using (Html.BeginForm("Create", "partrequisitions", FormMethod.Post, new { id = "form" } ))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    @Html.HiddenFor(c => c.idReference)
    @Html.HiddenFor(c => c.ReferenceNumber)
    @Html.HiddenFor(c => c.PartDescription)
    @Html.HiddenFor(c => c.PartNumber)
    @Html.HiddenFor(c => c.StockQTY)
    @Html.HiddenFor(c => c.PartType)
    @Html.HiddenFor(c => c.RequisitionQTY)

    <div class="modal-body">

        <table style="filter: alpha(opacity=40); opacity: 0.95;border:2px black solid;width:100%" ;table-layout:fixed;>
            <tr>
                <th colspan="4" bgcolor="#dddddd" cellspacing="1" cellpadding="6" style="font-size: 15px;border:1px black solid;padding-left:0.8ex">Part Information</th>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>

            <tr>
                <td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Part Category:</td>
                <td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap>@Html.DisplayFor(c => c.PartType)</td>
                <td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Part Number:</td>
                <td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap>@Html.DisplayFor(c => c.PartNumber)</td>
            </tr>
            <tr>
                <td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Description:</td>
                <td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap>@Html.DisplayFor(C => C.PartDescription)</td>

                <td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Stocked QTY:</td>
                <td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex">@Html.DisplayFor(C => C.StockQTY)</td>
            </tr>

        </table>
        <br />
        <table style="filter: alpha(opacity=40); opacity: 0.95;border:2px black solid;width:100%" ;table-layout:fixed;>
            <tr>
                <th colspan="5" bgcolor="#dddddd" cellspacing="1" cellpadding="6" style="font-size: 15px;border:1px black solid;padding-left:0.8ex">Order Information</th>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>

            <tr>
                <td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Vendor:</td>
                <td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap>
                    @Html.DropDownListFor(m => m.idVendor, Model.VendorNames, "-- Select Vendor --", new { @id = "VendorName1", style = "width: 200px;", required = "required" })
                    @Html.ValidationMessageFor(m => m.idVendor, "", new { @class = "text-danger" })
                </td>
                <td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Reference Number:</td>
                <td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap>@*@Html.DropDownListFor(m => m.idReference, Model.ReferenceNumbers, "-- Select Reference Number --", new { style = "width:900px", id = "ReferenceNumber1" })*@</td>
                <td></td>
            </tr>
            <tr>
                <td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Contact:</td>
                <td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap> @Html.DisplayFor(m => m.VendorContact) </td>

                <td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Vendor Number:</td>
                <td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap>@Html.DisplayFor(m => m.VendorPartNumber)</td>
                <td></td>

            </tr>
            <tr>
                <td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Vendor Price: ($)</td>
                <td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex">@Html.TextBoxFor(C => C.VendorPrice, new { htmlAttributes = new { @oncut = "return false", @oncopy = "return false", @onpaste = "return false", @type = "number", @min = "0", @max = "999", @id = "VendorPrice" }, style = "width:50px;" })</td>
                <td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Confirmed Price:</td>
                <td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex">
                    @Html.RadioButtonFor(c => c.ConfirmedPrice, 0) No @Html.RadioButtonFor(c => c.ConfirmedPrice, 1) Yes
                </td>
                <td></td>
            </tr>
            <tr>
                <td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Order Qty:</td>
                <td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex">@Html.TextBoxFor(c => c.RequisitionQTY, new { htmlAttributes = new { @oncut = "return false", @oncopy = "return false", @onpaste = "return false", @type = "number", @min = "0", @max = "999", @id = "RequisitionQTY" }, style = "width:50px;" })</td>
                <td></td>
                <td></td>
                <td></td>
            </tr>

        </table>
        <br />
    </div>
    <div class="modal-footer">

        <table class="center">
            <tr>
                <td style="text-align:center">
                    <input type="submit" value="Save" class="btn btn-primary" />
                </td>
                <td style="text-align:center"><button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button></td>
            </tr>
        </table>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Scripts/Appjs/PRequisitionCreate.js")

    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>

    <script type="text/javascript">
        $("form").removeData("validator");
        $("form").removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse("form");
    </script>

}

Create Form - Script File


$(document).ready(function () {
    $(window).keydown(function (event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            return false;
        }
    });
});


$("#RequisitionQTY").keydown(function (evt) {
    evt = (evt) ? evt : window.event;
    let charCode = (evt.which) ? evt.which : evt.keyCode;
    if ((charCode > 31 && ((charCode < 48 || charCode > 57) && (!(charCode >= 96 && charCode <= 105)))) && charCode != 46) {
        evt.preventDefault();
    }
    else {
        return true;
    }
});

$("#VendorPrice").keydown(function (evt) {
    evt = (evt) ? evt : window.event;
    let charCode = (evt.which) ? evt.which : evt.keyCode;
    if ((charCode > 31 && ((charCode < 48 || charCode > 57) && (!(charCode >= 96 && charCode <= 105)))) && charCode != 46 && charCode != 110) {
        evt.preventDefault();
    }
    else {
        return true;
    }
});

$("#VendorName1").change(function () {
    var tempID = document.getElementById("VendorName1");

    $.ajax({
        type: 'POST',
        url: '@Url.Action("LookupVendor", "partrequisitions")',
        dataType: 'json',
        data: { id: tempID },
        success: function (data) {
            $("#myModalContent").html(data);
        }
    });
});

ViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace MYSQL___Parts_Management.Models
{
    public class RequisitionOrder
    {
        //DropDownListFor data
        public RequisitionOrder()
        {
            this.VendorNames = new List<SelectListItem>();
        }
        public List<SelectListItem> VendorNames { get; set; }
        public int idVendor { get; set; }
        public int idReference { get; set; }

        //DisplayFor data
        public int ReferenceNumber { get; set; }
        public string PartType { get; set; }
        public string PartNumber { get; set; }
        public string PartDescription { get; set; }
        public int StockQTY { get; set; }
        public string VendorName { get; set; }
        public string VendorContact { get; set; }
        public string VendorPhone { get; set; }
        public string VendorPartNumber { get; set; }

        [DisplayFormat(DataFormatString = "{0:C}")]
        [Required(ErrorMessage = "Vendor Price required")]
        public decimal VendorPrice { get; set; }
        public int ConfirmedPrice { get; set; }
        public int RequisitionQTY { get; set; }
        public int ReceivedQTY { get; set; }
        public int PReceivedQTY { get; set; } /*Previously Received QTY*/
    }
}

Layout (Nav Bar)

<!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>@ViewBag.Title - My ASP.NET Application</title>
            @Styles.Render("~/Content/css")
            @Scripts.Render("~/bundles/modernizr")

        </head>
        <body>
            <div class="navbar navbar-inverse navbar-fixed-top">
                <div class="container">
                    <div class="navbar-header">
                        <a class="navbar-brand" href="/">
                            <img src="~/upload/logo.png" style="height:auto; width:30%; margin-top:-15px"/>
                        </a>
                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                        @Html.ActionLink("Part Management System", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                    </div>
                    <div class="navbar-collapse collapse">
                        <ul class="nav navbar-nav">

                            @if (Request.IsAuthenticated)
                            {
                                <li class="dropdown">
                                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="False">Help<span class="caret"></span></a>
                                    <ul class="dropdown-menu" role="menu">
                                        <li>@Html.ActionLink("About", "About", "Home")</li>
                                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                                    </ul>
                                </li>
                            }

                            @* Rest of Nav Menu truncated because of space. *@

                        </ul>
                        @Html.Partial("_LoginPartial")
                    </div>
                </div>
            </div>

            <div class="container body-content">
                @RenderBody()
                <hr />
                <footer>
                    <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
                </footer>
            </div>

            @Scripts.Render("~/bundles/jquery")
            @Scripts.Render("~/bundles/bootstrap")
            @RenderSection("scripts", required: false)
        </body>
        </html>

By excluding the _layout file from the partial view, the script file was not firing as expected. After a lengthy conversation with Patrick Hume, I Created a _blank layout file (as below) and everything was working as expected. It's probably not the cleanest way to do this. But it worked.

_blank layout

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  @Styles.Render("~/Content/css")
  @Scripts.Render("~/bundles/modernizr")
</head>

<body>
  <div class="container body-content">
    @RenderBody()
  </div>
   
  @Scripts.Render("~/bundles/jquery")
  @Scripts.Render("~/bundles/bootstrap")
  @RenderSection("scripts", required: false)
</body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM