Home > Back-end >  Textbox does not populate with database values when hyperlink is clicked
Textbox does not populate with database values when hyperlink is clicked

Time:11-30

When I run the page, and click on the value in the partial table nothing happens with the onclick event. the values are not populating on the textboxes.I set the style of the anchor element to cursor: pointer. Debugging the code as shown in the images, the values populate correctly they just do not appear in the textboxes.

index.cshtml

@page "{id?}"
@model IndexModel

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

<div >
    <div >
        <div >
            <h1 >@Model.PageTitle</h1>
        </div>
    </div>
    <div >
        <form  method="get">
            <div >
                <div  id="ApplicationResult">
                </div>
                <div  id="ApplicationOwnerResult">
                </div>
                <div  id="ApplicationDmvResult">
                </div>
            </div>
        </form>
    </div>
    <div >
        <form  method="post">
            <div >
                <label >Date of Birth:</label>
                <div >
                    <input  title="Date of birth" oninput="validate()" asp-for="DateOfBirth">
                    <span asp-validation-for="DateOfBirth"></span>
                </div>
            </div>
            <br>
            <div >
                <label >Driver's License Number:</label>
                <div >
                    <input  title="Driver's license number" oninput="validate()" asp-for="DriversLicenseNumber">
                    <span asp-validation-for="DriversLicenseNumber"></span>
                </div>
            </div>
            <br>
            <div >
                <button  type="submit" id="Submit" disabled asp-page-handler="Submit">Submit</button>
                &nbsp;
                <button  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>
}

index.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 });
        }

DbContext.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 model

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 model

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 model

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 >
            <thead>
                <tr>
                    <th  colspan="3">Exemption Applications</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td >@Html.DisplayNameFor(m => m.YearId)</td>
                    <td >@Html.DisplayNameFor(m => m.ApplicationReference)</td>
                    <td >@Html.DisplayNameFor(m => m.ExemptionApplicationId)</td>
                </tr>
                @foreach (Models.ExemptionApplication item in Model)
                {
                    <tr>
                        <td >@item.YearId</td>
                        <td >@item.ApplicationReference</td>
                        <td >
                            <a  href="Index/?handler=DisplayOwner&[email protected]">@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 >
            <thead>
                <tr>
                    <th  colspan="3">Owner Information</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td >@Html.DisplayNameFor(m => m.ExemptionApplicationOwnerId)</td>
                    <td  colspan="2">@Html.DisplayNameFor(m => m.AssessProName)</td>
                </tr>
                @foreach (Models.ExemptionApplicationOwner item in Model)
                {
                    <tr>
                        <td >
                           <a  onclick="displayOwnerInfo('@item.ExemptionApplicationOwnerId')">@item.ExemptionApplicationOwnerId</a>
                      <!-- <a  href="Index/?handler=DisplayOwnerInfo&[email protected]">@item.ExemptionApplicationOwnerId</a> -->
                        </td>
                        <td >@item.FirstName</td>
                        <td >@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>
}

enter image description here

enter image description here

enter image description here

CodePudding user response:

Scripts in Partials which are themselves loaded by script will not execute. You should place the code that adds the click event handler to the #OwnerNav a element(s) to Index.cshtml. However, you need to use the on method and apply it to an element that exists when the page is initially rendered (e.g. 'body'), passing in the target selector after the name of the event handler:

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

CodePudding user response:

Try to change your ajax like below:

success: function (data) { 
$("#DateOfBirth").val(data.dateOfBirth);                     
$("#DriversLicenseNumber").val(data.driversLicenseNumber);                 
}

then add id="DateOfBirth" and id="DriversLicenseNumber" into your input :

<input  title="Date of birth" oninput="validate()" name="DateOfBirth" id="DateOfBirth">
<input  title="Driver's license number" oninput="validate()" name="DriversLicenseNumber"id="DriversLicenseNumber">
  • Related