how to add multiple of model in one view - javascript

I want to add my class model in my index view because I need ClassID for dropdown to show classes in my view but don't know how to.
This is my index:
#using opr.Models;
#using PagedList;
#using PagedList.Mvc;
#model PagedList.IPagedList<opr.Data.C_QuestionTable>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="alert-success form-control m-auto w-75 custom-form">
<div class="col-6 pb-3 input-control">
<label for="ex3"> Select Class:</label>
#Html.DropDownListFor(model => model.ClassID, (SelectList)ViewBag.dataForDropDowns, new { #class = "form-control select2ddl" })
</div>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
QuestionText
</th>
</tr>
#foreach (var item in Model)
{
foreach (var answer in item.C_AnswerTable)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.QuestionText)
#Html.RadioButton("searchBy", answer.Options, true)
<text>#answer.Options</text>
</td>
</tr>
}
}
<tr>
<div class="pagination pull-left">
<hr />
<td colspan="3">#Html.PagedListPager(Model, page => Url.Action("Index", new { page = page }))</td>
</div>
</tr>
</table>
</div>
This is my Controller:
examsEntities db = new examsEntities();
public ActionResult Index(int?page)
{
var mod1 = db.myclasses.Select(s => new { s.ID, s.C_name }).ToList();
SelectList sList = new SelectList(mod1, "ID", "C_name");
ViewBag.dataForDropDown = sList;
var pageNumber = page ?? 1;
var pageSize = 3;
var question = db.C_QuestionTable.OrderBy(x => x.QuestionText).ToPagedList(pageNumber, pageSize);
return View(question);
}

namespace OMS.Models
{
public class AbcModel
{
public int Id { get; set; }
public string Name{ get; set; }
public Classmodel classmodel{ get; set; }
}
}
bind class model into Index model(Abc model) and now in view
#using opr.Models;
#using PagedList;
#using PagedList.Mvc;
#model PagedList.IPagedList<opr.Data.C_QuestionTable>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="alert-success form-control m-auto w-75 custom-form">
<div class="col-6 pb-3 input-control">
<label for="ex3"> Select Class:</label>
#Html.DropDownListFor(model => model.classmodel.ClassID,
(SelectList)ViewBag.dataForDropDowns, new { #class = "form-control
select2ddl" })
</div>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
QuestionText
</th>
</tr>
#foreach (var item in Model)
{
foreach (var answer in item.C_AnswerTable)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.QuestionText)
#Html.RadioButton("searchBy", answer.Options, true)
<text>#answer.Options</text>
</td>
</tr>
}
}
<tr>
<div class="pagination pull-left">
<hr />
<td colspan="3">#Html.PagedListPager(Model, page => Url.Action("Index", new { page = page }))</td>
</div>
</tr>
</table>
</div>
Hope it will help you

Related

How to display pagination on View of action Index?

I work on asp.net core 5 vs 2019 i face issue I can't display Pagination of view action Index of controller Cinemas .
what I try is
1- create custom view model for Cinemas as below :
public class CinmaPageViewModel
{
public IEnumerable<CinimaViewModels> Cinmas { get; set; }
public Pager Pager { get; set; }
}
public class CinimaViewModels
{
public string Logo { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class Pager
{
public int NumberOfPages { get; set; }
public int CurrentPage { get; set; }
public int TotalRecords { get; set; }
}
2-create service and implementation class inheritance
public interface ICinemasService:IEntityBaseRepository<Cinema>
{
IQueryable<CinimaViewModels>GetAllCinimas();
}
public class CinemasService:EntityBaseRepository<Cinema>, ICinemasService
{
private readonly AppDbContext _context;
public CinemasService(AppDbContext context) : base(context)
{
_context = context;
}
public CinemasService(AppDbContext context) : base(context)
{
_context = context;
}
public IQueryable<CinimaViewModels> GetAllCinimas()
{
var response = _context.Cinemas.Select(x => new CinimaViewModels() { Logo = x.Logo, Name = x.Name,Description=x.Description });
return response;
}
3- on controller I return custom model view CinmaPageViewModel
[AllowAnonymous]
public IActionResult Index(int pageNumber = 1)
{
var allCinemas = _service.GetAllCinimas();
var result = _pageHelper.GetPage(allCinemas.AsQueryable(), pageNumber);
var cinimas = new CinmaPageViewModel
{
Cinmas = result.Items,
Pager = result.Pager
};
return View(cinimas);
}
4-I create view Index as Index.cshtml for action Index as below
<div class="row">
<div class="col-md-8 offset-md-2">
<table class="table">
<thead>
<tr class="text-center">
<th>logo</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Cinmas)
{
<tr>
<td class="align-middle">
<img class="rounded-circle" src="#item.Logo" alt="#item.Name" style="max-width: 150px" />
</td>
<td class="align-middle">
#Html.DisplayFor(modelItem => item.Name)
</td>
<td class="align-middle">
#Html.DisplayFor(modelItem => item.Description)
</td>
</tr>}
</tbody>
</table>
</div>
</div>
How to display pagination on index.cshtml view for action Index
controller name Cinemas
There are many methods to achieve pagination, Here I will show a simple demo about how to display pagination, Hope it can give you some help.
First add two properties in Pager model:
public class Pager
{
public int NumberOfPages { get; set; }
public int CurrentPage { get; set; }
public int TotalRecords { get; set; }
public bool HasPreviousPage { get; set; }
public bool HasNextPage { get; set; }
}
In your code, there are some methods you don't provide. From the name of
_service.GetAllCinimas(); , I think this method is to get all Cinimas. Then I write my own GetPage() method:
static CinmaPageViewModel GetPage(List<CinimaViewModels> model,int currentpage)
{
var totalrecode = model.Count();
//I set each page can show 3 recods;
var pagesize = 3;
//Get cinimals
var result = model.Skip(pagesize*(currentpage-1)).Take(pagesize);
var TotalPages = (int)Math.Ceiling(totalrecode / (double)pagesize);
Pager page = new Pager();
page.CurrentPage = currentpage;
page.TotalRecords = totalrecode;
page.NumberOfPages = TotalPages;
page.HasPreviousPage = (currentpage > 1);
page.HasNextPage = (currentpage < TotalPages);
CinmaPageViewModel resultmodel = new CinmaPageViewModel()
{
Cinmas = result.ToList(),
Pager = page
};
return resultmodel;
}
Action
public IActionResult Show(int pageNumber = 1)
{
var cinimalsAll = _service.GetAllCinimas();
var result = GetPage(cinimalsAll,pageNumber)
return View(result);
}
View
#model CinmaPageViewModel
<div class="row">
<div class="col-md-8 offset-md-2">
<table class="table">
<thead>
<tr class="text-center">
<th>logo</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Cinmas)
{
<tr>
<td class="align-middle">
<img class="rounded-circle" src="#item.Logo" alt="#item.Name" style="max-width: 150px" />
</td>
<td class="align-middle">
#Html.DisplayFor(modelItem => item.Name)
</td>
<td class="align-middle">
#Html.DisplayFor(modelItem => item.Description)
</td>
</tr>
}
</tbody>
</table>
#{
var prevDisabled = !Model.Pager.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.Pager.HasNextPage ? "disabled" : "";
}
<a asp-action="Show"
asp-route-pageNumber="#(Model.Pager.CurrentPage -1 )"
class="btn btn-default #prevDisabled">
Previous
</a>
#Model.Pager.CurrentPage/#Model.Pager.NumberOfPages
<a asp-action="Show"
asp-route-pageNumber="#(Model.Pager.CurrentPage + 1)"
class="btn btn-default #nextDisabled">
Next
</a>
</div>
</div>
Demo
Update:
#{
var prevDisabled = !Model.Pager.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.Pager.HasNextPage ? "disabled" : "";
}
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-center">
<li class="page-item disabled">
<a asp-action="Show" asp-route-pageNumber="#(Model.Pager.CurrentPage -1 )" class="btn btn-default #prevDisabled">Previous</a>
</li>
#for (int i = 0; i < Model.Pager.NumberOfPages; i++)
{
<li class="page-item"><a class="page-link" asp-action="Show" asp-route-pageNumber="#(i+1)">#(i+1)</a></li>
}
<li class="page-item">
<a asp-action="Show" asp-route-pageNumber="#(Model.Pager.CurrentPage + 1)" class="btn btn-default #nextDisabled">Next</a>
</li>
</ul>
</nav>
demo:

Autofill input textboxes from clicking a hyperlink on a partial view

please refer to the image, when I click on the link on the left partial table, instead of having the values display on a separate partial table view as shown, I'd like the values to be autofilled in the bottom 2 textboxes to avoid having to click and drag the values and to have the date formatted to 01312000 format
index.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>
<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();
}
});
</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());
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 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" 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>
}
Before check the demo, you need to know one thing, if your DateOfBirth is type of Datetime, you need be sure or convert it to format yyyy-MM-ddThh:mm. Otherwise, you could only set value for the type=datetime-local input without displaying the value.
Here is a simple demo about how to autofill the textbox value by clicking your table link:
Index.cshtml:
#page
#model IndexModel
<form class="mt-0" method="get">
<div class="row">
<div class="col-4" id="ApplicationOwnerResult">
</div>
</div>
</form>
<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>
</form>
</div>
#section Scripts
{
<script>
//used to render the partial view _DisplayOwnerPartial.cshtml....
$(function(){
$.ajax({
url: "/Index?handler=DisplayOwner",
type: "Get",
//headers: { RequestVerificationToken: $('input: hidden[name="__RequestVerificationToken"]').val() },
success: function (data) { $("#ApplicationOwnerResult").html(data); }
});
})
//auto fill the inputs...
function DisplayInfo(id) {
$.ajax({
url: "Index/?handler=DisplayOwnerInfo&value="+id,
type: "Get",
success: function (data) {
$("#DateOfBirth").val(data.dateOfBirth);
$("#DriversLicenseNumber").val(data.driversLicenseNumber);
}
})
}
</script>
}
_DisplayOwnerPartial.cshtml:
#model IEnumerable<Models.ExemptionApplicationOwner>
#if (Model.Count() != 0)
{
<div id="OwnerNav">
<table class="PartialTable">
<tbody>
#foreach (Models.ExemptionApplicationOwner item in Model)
{
<tr>
<td class="PartialTableRowData">
<a class="DMVLabelsTexts" onclick="DisplayInfo('#item.ExemptionApplicationOwnerId')" >#item.ExemptionApplicationOwnerId</a>
</td>
</tr>
}
</tbody>
</table>
</div>
}
Index.cshtml.cs:
For easy testing, I just hard-coded the data. You can get the data from database.
public class IndexModel : PageModel
{
public DateTime DateOfBirth { get; set; }
public int DriversLicenseNumber { get; set; }
public List<ExemptionApplicationOwner> ExemptionApplicationOwners { get; set; }= new List<ExemptionApplicationOwner>()
{
new ExemptionApplicationOwner(){ExemptionApplicationOwnerId=1,DateOfBirth=new DateTime(1987,3,12),DriversLicenseNumber=124},
new ExemptionApplicationOwner(){ExemptionApplicationOwnerId=2,DateOfBirth=new DateTime(1997,2,11),DriversLicenseNumber=332},
new ExemptionApplicationOwner(){ExemptionApplicationOwnerId=3,DateOfBirth=new DateTime(1987,5,23),DriversLicenseNumber=445}
};
public void OnGet()
{
}
public IActionResult OnGetDisplayOwner()
{
return Partial("_DisplayOwnerPartial", ExemptionApplicationOwners);
}
public JsonResult OnGetDisplayOwnerInfo(int value)
{
var data = ExemptionApplicationOwners.Where(a => a.ExemptionApplicationOwnerId == value).First();
return new JsonResult(new { DateOfBirth =data.DateOfBirth.ToString("yyyy-MM-ddThh:mm"), DriversLicenseNumber=data.DriversLicenseNumber });
}
}
I made the adjustments per Renas comments and I'm still having an issue with the values not autofilling. When I run the page, and click on the value in the partial table nothing happens with the onclick event. I set the style of the anchor element to cursor: pointer, below are the changes I made. 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 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>
<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>
}
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 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>
}

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('' + pageNum + ' ');
}
$('#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">
Help<span class="caret"></span>
<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>© #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>

Pass the value of a button to a hidden field and save it to database

So my design is I have multiple display fields and one hidden field. Besides each row there are two buttons accept and reject.my point is when I click a button its value pass to the hidden field and submits automatically in the database.
when I try my code the button doesn't pass anything and I tried all the solutions related to this topic and nothing is working. what am I doing wrong?
controller:
[HttpGet]
public ActionResult Add_Fulfillment ()
{
var getData = db.TBL_Request.Include(x=>x.TBL_Accounts).Include(x=>x.TBL_Accounts_LOBs).ToList() ;
var add_fulfillment = new Add_Fulfillment();
var ful_ = new fulfillmentVM();
foreach (var data in getData)
{
List<Add_Fulfillment> fulfillment = db.TBL_Request.Select(i => new Add_Fulfillment
{
Request_ID = i.Request_ID,
Employee_no = i.Employee_no,
Operation_Date = i.Operation_Date,
Fulfillment_Rate = i.Fulfillment_Rate ??0,
Account_Name = i.TBL_Accounts.Account_Name,
LOB = i.TBL_Accounts_LOBs.LOB,
Status = i.Inserted_by
}).ToList();
ful_._Requests = fulfillment;
}
return View(ful_);
}
[HttpPost]
public ActionResult Add_Fulfillment_Accept(int Request_ID , int? Status)
{
var user= db.TBL_Request.Find(Request_ID);
//hiddenfieldvalue assigns it to the field in the database i want to update
db.SaveChanges();
return RedirectToAction("Add_Fulfillment");
}
[HttpPost]
public ActionResult Add_Fulfillment_Reject(int Request_ID)
{
return RedirectToAction("Add_Fulfillment");
}
the view
#model Staff_Requisition.Models.fulfillmentVM
#{
ViewBag.Title = "Add_Fulfillment";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Add_Fulfillment</h2>
<!-- page content -->
<div class="right_col" role="main">
<div class="">
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Plain Page</h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<table class="table">
<tr>
<th>
Employee_no
</th>
<th>
Operation_Date
</th>
<th>
Fulfillment_Rate
</th>
<th>
Account_Name
</th>
<th>
LOB
</th>
<th></th>
<th></th>
</tr>
#for (int i = 0; i < Model._Requests.Count(); i++)
{
<tr>
<td>
#Html.DisplayFor(x => Model._Requests[i].Employee_no)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].Operation_Date)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].Fulfillment_Rate)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].Account_Name)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].LOB)
</td>
<td>
#Html.Hidden("Status" , Model._Requests[i].Status , new { id = "myEdit" })
</td>
#using (Html.BeginForm("Add_Fulfillment_Accept", "TBL_Request", FormMethod.Post, new { #id = "myForm" }))
{
#Html.AntiForgeryToken()
<td>
<button id="btnAccept" class="btn btn-lg btn-success" name="a_button" type="submit" value="122">Accept</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
</td>
}
#using (Html.BeginForm("Add_Fulfillment_Reject", "TBL_Request", FormMethod.Post, new { #id = "myForm" }))
{
#Html.AntiForgeryToken()
<td>
<button id="btnReject" class="btn btn-lg btn-danger" name="button" type="submit" value="222">Reject</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
</td>
}
</tr>
}
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /page content -->
#section Scripts {
<script>
$("#btnAccept").click(function () {
$("#myEdit").val($("#btnAccept").val());
})
$("#btnReject").click(function () {
$("#myEdit").val($("#btnReject").val());
})
</script>
}
I solved it. the only issue was I didn't put the hidden field of the status inside the form .that's why it never passes the value. thank you for all your efforts though!
view:
#using (Html.BeginForm("Add_Fulfillment_Accept", "TBL_Request", FormMethod.Post))
{
#Html.AntiForgeryToken()
<td>
<button id="btnAccept" class="btn btn-lg btn-success" name="a_button" type="submit" onclick="accept(122)" value="122">Accept</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
#Html.Hidden("Status", Model._Requests[i].Status, new { id = "myEdit", value = "" })
</td>
}
#using (Html.BeginForm("Add_Fulfillment_Reject", "TBL_Request", FormMethod.Post))
{
#Html.AntiForgeryToken()
<td>
<button id="btnReject" class="btn btn-lg btn-danger" name="button" type="submit" onclick="reject(222)" value="222">Reject</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
#Html.Hidden("Status", Model._Requests[i].Status, new { id = "myEdit", value = "" })
</td>
}
</tr>
}
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /page content -->
#section Scripts {
<script>
$('[name = "a_button"]').click(function () {
$('[name = "Status"]').val($('[name = "a_button"]').val());
})
$('[name = "button"]').click(function () {
$('[name = "Status"]').val($('[name = "button"]').val());
})
</script>

How to bind dropdown value in mvc

I'm unable to bind the dropdown value. Maybe I'm missing something in my code. Here I'm attaching my view code.
<tr>
<td>
<div class="form-group" style="margin-bottom:0px;">
#Html.DropDownList("ProofId", ViewBag.Idproofs as SelectList, new { #class = "form-control", id = "ProofType2", name = "ProofType2" })
</div>
</td>
<td>
<div class="form-group" style="margin-bottom:0px;">
#Html.TextBoxFor(x => x.EvidenceData[1].ProofNumber, new { #class = "form-control", id = "IdNumber2", name = "IdNumber2" })
</div>
</td>
<td>
<div class="form-group" style="margin-bottom:0px;">
#Html.TextBoxFor(x => x.EvidenceData[1].ProofImage, new { #class = "form-control", id = "ProofPic2", type = "file", name = "ProofPic2" })
<i class="fa fa-download" aria-hidden="true"></i> Download Image
</div>
</td>
</tr>
And this is my controller code:
public ActionResult EditProfile(string country)
{
if (!User.Identity.IsAuthenticated)
return new RedirectResult(Utility.Config("RedirectPath"));
var idprooflist = AccountManager.LoadProoftypes(country ?? "United States");
ViewBag.Idproofs = new SelectList(idprooflist, "ProofId", "ProofName");
UserRegistration UserProfileData = ProviderManagerBLL.GetProviderDetails(Convert.ToInt32(Session["UserID"].ToString()));
return View(UserProfileData);
}
The below should work for you:
<div class="form-group" style="margin-bottom:0px;">
#Html.DropDownList("ProofId", (SelectList)ViewBag.Idproofs, new { #class = "form-control", id = "ProofType2", name = "ProofType2" })
</div>
You are using a ViewBag to pass your values to the View and all you have to do is reference what you want from it. What you were doing before wouldn't work

Categories

Resources