【问题标题】:Textbox does not populate with database values when hyperlink is clicked单击超链接时,文本框不会填充数据库值
【发布时间】:2022-11-30 04:16:55
【问题描述】:

当我运行该页面并单击部分表中的值时,onclick 事件没有任何反应。这些值未填充在文本框上。我将锚元素的样式设置为光标:指针。如图所示调试代码,值正确填充,只是没有出现在文本框中。

索引.cshtml

@page "{id?}"
@model IndexModel

@{ViewData["Title"] = "Test";}

<div class="container">
    <div class="row">
        <div class="text-center">
            <h1 class="display-4">@Model.PageTitle</h1>
        </div>
    </div>
    <div class="row">
        <form class="mt-0" method="get">
            <div class="row">
                <div class="col-3 offset-1" id="ApplicationResult">
                </div>
                <div class="col-4" id="ApplicationOwnerResult">
                </div>
                <div class="col-3" id="ApplicationDmvResult">
                </div>
            </div>
        </form>
    </div>
    <div class="row">
        <form class="mt-0" method="post">
            <div class="row">
                <label class="col-2 offset-4 col-form-label">Date of Birth:</label>
                <div class="col-2">
                    <input class="form-control" title="Date of birth" oninput="validate()" asp-for="DateOfBirth">
                    <span asp-validation-for="DateOfBirth"></span>
                </div>
            </div>
            <br>
            <div class="row">
                <label class="col-2 offset-4 col-form-label">Driver's License Number:</label>
                <div class="col-2">
                    <input class="form-control" title="Driver's license number" oninput="validate()" asp-for="DriversLicenseNumber">
                    <span asp-validation-for="DriversLicenseNumber"></span>
                </div>
            </div>
            <br>
            <div class="row">
                <button class="btn btn-outline-dark col-1 offset-5" type="submit" id="Submit" disabled asp-page-handler="Submit">Submit</button>
                &nbsp;
                <button class="btn btn-outline-dark col-1" type="button" id="Reset" onclick="clearAll()">Reset</button>
            </div>
            <br>
        </form>
    </div>
</div>

@section Scripts {
<script>
// Any exemption applications found will be displayed when the page initially loads. On POST request GET form will be hidden
    $(document).ready(function () {
        if ("@Model.Exist" == "DivIsVisible") {
            $.ajax({
                url: "Index/?handler=Display",
                type: "GET",
                data: { value: @Model.Id },
                headers: { RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val() },
                success: function (data) { $("#ApplicationResult").html(data); }
            });
        }
        else {
            $("#ApplicationResult").hide();
        }
    });

// autofill the inputs
    function displayOwnerInfo(id) {
        $.ajax({
            url: "Index/?handler=DisplayOwnerInfo&value=" + id,
            type: "GET",
            success: function (data) { $("#DateOfBirth").val(data.DateOfBirth); $("#DriversLicenseNumber").val(data.DriversLicenseNumber); }
        });
    }
</script>
}

索引.cshtml.cs

using DMVServiceReference;
using DMV.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Threading.Tasks;

namespace DMV.Pages
{
    public class IndexModel : PageModel
    {
        public Assess50Context _context;

        // Id property refers to checking the PropertyId value for the URL
        [BindProperty(SupportsGet = true)] public int Id { get; set; }
        // Exist property refers to checking if GetDivs exist on POST request
        [BindProperty] public string PageTitle { get; set; } = "Residency Check";
        public ResidencyCheckCriteria CheckCriteria { get; set; }
        [BindProperty, DataMember, MaxLength(8, ErrorMessage = " "), MinLength(8, ErrorMessage = " "), RegularExpression(@"^([0-9]{8}$)", ErrorMessage = " "), Required(ErrorMessage = " ")] public string DateOfBirth { get => CheckCriteria.DateOfBirth; set => CheckCriteria.DateOfBirth = value; }
        [BindProperty, DataMember, MaxLength(13, ErrorMessage = " "), MinLength(13, ErrorMessage = " "), RegularExpression(@"^([A-Za-z0-9]{13}$)", ErrorMessage = " "), Required(ErrorMessage = " ")] public string DriversLicenseNumber { get => CheckCriteria.DriverLicenseNumber; set => CheckCriteria.DriverLicenseNumber = value; }
        [BindProperty(SupportsGet = true)] public string Exist { get; set; } = "DivIsVisible";

        public IndexModel(Assess50Context context)
        {
            _context = context;
            CheckCriteria = new ResidencyCheckCriteria();
        }

        // Reads all exemption application table information by property id
        public PartialViewResult OnGetDisplay(int value) => Partial("_DisplayApplicationPartial", _context.ExemptionApplications.Where(x => x.PropertyId == value).ToList());

        // Reads all exemption application owner information by exemption application id
        public PartialViewResult OnGetDisplayOwner(int value) => Partial("_DisplayOwnerPartial", _context.ExemptionApplicationOwners.Where(x => x.ExemptionApplicationId == value).GroupBy(x => x.ExemptionApplicationOwnerId).Select(x => x.First()).ToList());

        // Reads the dmv information by application owner ID
        // public PartialViewResult OnGetDisplayOwnerInfo(int value) => Partial("_DisplayDMVPartial", _context.ExemptionApplicationDmvinformations.Where(x => x.ExemptionApplicationOwnerId == value).ToList());
        public JsonResult OnGetDisplayOwnerInfo(int value)
        {
            ExemptionApplicationDmvinformation data = _context.ExemptionApplicationDmvinformations.Where(x => x.ExemptionApplicationOwnerId == value).First();
            return new JsonResult(new { DateOfBirth = data.DmvDob.ToString(), DriversLicenseNumber = data.DriverLicense });
        }

数据库上下文.cs

using Microsoft.EntityFrameworkCore;

namespace DMV.Models
{
    public partial class Assess50Context : DbContext
    {
        public virtual DbSet<ExemptionApplication> ExemptionApplications { get; set; } = null!;
  public virtual DbSet<ExemptionApplicationDmvinformation> ExemptionApplicationDmvinformations { get; set; } = null!;
 public virtual DbSet<ExemptionApplicationOwner> ExemptionApplicationOwners { get; set; } = null!;

 public Assess50Context() {}

        public Assess50Context(DbContextOptions<Assess50Context> options) : base(options) {}

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
  }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

Application.cs模型

using System;
using System.ComponentModel.DataAnnotations;

namespace DMV.Models
{
    public partial class ExemptionApplication
    {
        public int PropertyId { get; set; }
        [Display(Name = "Year")] public short YearId { get; set; }
        [Display(Name = "App ID")] public int ExemptionApplicationId { get; set; }
        [Display(Name = "Reference Number")] public string? ApplicationReference { get; set; }
    }
}

Owner.cs模型

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace DMV.Models
{
    public partial class ExemptionApplicationOwner
    {
        public int PropertyId { get; set; }
        public int ExemptionApplicationId { get; set; }
        [Display(Name = "Application Owner ID")] public int ExemptionApplicationOwnerId { get; set; }
        [Display(Name = "Owner ID")] public int? OwnerId { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        [Display(Name = "Name")]public string? AssessProName { get; set; }
    }
}

DmvInformation.cs模型

using SoapCore.ServiceModel;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace DMV.Models
{
    public partial class ExemptionApplicationDmvinformation
    {
        public int PropertyId { get; set; }
        public int ExemptionApplicationId { get; set; }
        public int ExemptionApplicationOwnerId { get; set; }
        [Display(Name = "DOB")] public DateTime? DmvDob { get; set; }
        [Display(Name = "Driver's License #")] public string? DriverLicense { get; set; }
    }
}

_DisplayApplicationPartial.cshtml

@model IEnumerable<Models.ExemptionApplication>

@if (Model.Count() != 0)
 {
    <div id="ExemptionApplicationNav">
        <table class="PartialTable">
            <thead>
                <tr>
                    <th class="PartialTableRowData" colspan="3">Exemption Applications</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="PartialTableRowCategoryData">@Html.DisplayNameFor(m => m.YearId)</td>
                    <td class="PartialTableRowCategoryData">@Html.DisplayNameFor(m => m.ApplicationReference)</td>
                    <td class="PartialTableRowCategoryData">@Html.DisplayNameFor(m => m.ExemptionApplicationId)</td>
                </tr>
                @foreach (Models.ExemptionApplication item in Model)
                {
                    <tr>
                        <td class="PartialTableRowData">@item.YearId</td>
                        <td class="PartialTableRowData">@item.ApplicationReference</td>
                        <td class="PartialTableRowData">
                            <a class="DMVLabelsTexts" href="Index/?handler=DisplayOwner&value=@item.ExemptionApplicationId">@item.ExemptionApplicationId</a>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
 }
else
{
    <p>No exemption applications found for this Property ID</p>
}
    <script>
        $('#ExemptionApplicationNav a').click(function (e) {
            $('#ApplicationOwnerResult').hide().load($(this).attr('href'), function () {
                $('#ApplicationOwnerResult').show()
            })
            return false
        })
    </script>

_DisplayOwnerPartial.cshtml

@model IEnumerable<Models.ExemptionApplicationOwner>

@if (Model.Count() != 0)
{
    <div id="OwnerNav">
        <table class="PartialTable">
            <thead>
                <tr>
                    <th class="PartialTableRowData" colspan="3">Owner Information</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="PartialTableRowCategoryData">@Html.DisplayNameFor(m => m.ExemptionApplicationOwnerId)</td>
                    <td class="PartialTableRowCategoryData" colspan="2">@Html.DisplayNameFor(m => m.AssessProName)</td>
                </tr>
                @foreach (Models.ExemptionApplicationOwner item in Model)
                {
                    <tr>
                        <td class="PartialTableRowData">
                           <a class="DMVLabelsTexts" onclick="displayOwnerInfo('@item.ExemptionApplicationOwnerId')">@item.ExemptionApplicationOwnerId</a>
                      <!-- <a class="DMVLabelsTexts" href="Index/?handler=DisplayOwnerInfo&value=@item.ExemptionApplicationOwnerId">@item.ExemptionApplicationOwnerId</a> -->
                        </td>
                        <td class="PartialTableRowMultipleData">@item.FirstName</td>
                        <td class="PartialTableRowMultipleData">@item.LastName</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
}
else
{
    <p>No owner data available</p>
}
 <!--
    <script>
        $('#OwnerNav a').click(function (e) {
              $('#ApplicationDmvResult').hide().load($(this).attr('href'), function () {
                  $('#ApplicationDmvResult').show()
              })
              return false
        })
    </script>
-->

_DisplayDMVPartial.cshtml

@model IEnumerable<Models.ExemptionApplicationDmvinformation>

@if (Model.Count() != 0)
{
    <div id="DmvNav">
        <table style=" border: 1px solid black;">
            <thead>
                <tr>
                    <th colspan="2" style="border: 1px solid black; text-align: center;">DMV Information</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td style="border: 1px solid black; font-weight: bold; text-align: center;">@Html.DisplayNameFor(m => m.DmvDob)</td>
                    <td style="border: 1px solid black; font-weight: bold; text-align: center;">@Html.DisplayNameFor(m => m.DriverLicense)</td>
                </tr>
                @foreach (Models.ExemptionApplicationDmvinformation item in Model)
                {
                    <tr>
                        <!-- <td style="border: 1px solid black; text-align: center;">item.DmvDob.Value.ToString("MMddyyyy")</td> -->
                        <td style="border: 1px solid black; text-align: center;">@item.DmvDob</td>
                        <td style="border: 1px solid black; text-align: center;">@item.DriverLicense</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
}
else
{
    <p>No owner data available</p>
}

【问题讨论】:

    标签: javascript c# jquery asp.net-core razor-pages


    【解决方案1】:

    本身由脚本加载的 Partials 中的脚本将不会执行。您应该将添加点击事件处理程序的代码放置到 #OwnerNav a 元素中索引.cshtml.但是,您需要使用 on 方法并将其应用于页面最初呈现时存在的元素(例如“body”),在事件处理程序名称后传入目标选择器:

    $('body').on('click', '#OwnerNav a', function (e) {
        // 
    

    【讨论】:

    • 感谢您的建议,我尝试了您发布的内容,但仍未填充值。这是我根据您的建议所做的 $('body').on('click', '#OwnerNav a', function DisplayInfo(e) { $.ajax({ url: "Index/?handler=DisplayOwnerInfo&amp;value=" + e, type: "GET", success: function (data) { $("#DateOfBirth").val(data.DateOfBirth); $("#DriversLicenseNumber").val(data.DriversLicenseNumber); } }); })
    猜你喜欢
    • 2013-02-17
    • 2018-06-26
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 2012-07-31
    相关资源
    最近更新 更多