Thymeleaf form submit with ArrayList Object - javascript

I have written a simple program for form submit with the data(ArrayList) to send from table to controller class.
While submitting the form the data is always empty not sure what I am doing wrong here.
I am almost spending a lot of time to identify the issue no luck :(
Controller Class ( Where I always getting null in Post method )
public class AccountContoller {
private ArrayList<AccountwithSelection> allAccountwithSelect = new ArrayList<AccountwithSelection>();
public AccountContoller()
{
//Written some test data in Array
AccountwithSelection accountwithSelection1 = new AccountwithSelection();
accountwithSelection1.setAccountnumber("Acct1");
accountwithSelection1.setIlc("ILC1");
allAccountwithSelect.add(accountwithSelection1);
AccountwithSelection accountwithSelection2 = new AccountwithSelection();
accountwithSelection2.setAccountnumber("Acct2");
accountwithSelection1.setIlc("ILC2");
allAccountwithSelect.add(accountwithSelection2);
}
#RequestMapping(value = "/accountload", method = RequestMethod.GET)
String accountload(Model model) {
AccountSelectionListWrapper wrapper = new AccountSelectionListWrapper();
wrapper.setAccountList(allAccountwithSelect);
model.addAttribute("accountload", wrapper);
return "accountload";
}
#RequestMapping(value = "/accountload", method = RequestMethod.POST)
public String addimeiPost(Model model,
#ModelAttribute("accountload") AccountSelectionListWrapper wrapper,
HttpServletRequest request) {
System.out.println(wrapper.getAccountList()); //Always getting null, why ?
return "accountload";
}
}
Class: AccountwithSelection
public class AccountwithSelection {
public String accountnumber, ilc;
public String getAccountnumber() {
return accountnumber;
}
public void setAccountnumber(String accountnumber) {
this.accountnumber = accountnumber;
}
public String getIlc() {
return ilc;
}
public void setIlc(String ilc) {
this.ilc = ilc;
}
}
WrapperClass- AccountSelectionListWrapper
public class AccountSelectionListWrapper {
public ArrayList<AccountwithSelection> accountList;
public ArrayList<AccountwithSelection> getAccountList() {
return accountList;
}
public void setAccountList(ArrayList<AccountwithSelection> accountList) {
this.accountList = accountList;
}
}
HTML Form:(accountload.html)
<form action="#" th:action="accountload" th:object="${accountload}" method="post">
<div class="row">
<div class=form-group-1>
<input type="submit" value="Send Data" name="action">
</div>
</div>
<table id="mytable" class="table">
<tbody class="table-tbody" style="width: 90%">
<tr class="table-head">
<th>ACCOUNT NUMBER</th>
</tr>
<tr class="table-row">
<tr class="table-row" th:each="account, stat : *{accountList}">
<td class="table-data" th:text="${account.getAccountnumber()}"
th:field="*{accountList[__${stat.index}__].accountnumber}"
th:value="${account.getAccountnumber()}"></td>
</tr>
</tbody>
</table>
</form>

<td /> elements aren't submitted with a form. You need to use some kind of input. It should look something like this:
<td class="table-data">
<input type="text" th:field="*{accountList[__${stat.index}__].accountnumber}" />
</td>
or if you want to submit without seeing the fields as editable, something like this
<td class="table-data">
<span th:text="${account.accountnumber}" />
<input type="hidden" th:field="*{accountList[__${stat.index}__].accountnumber}" />
</td>

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>
}

.Net Core Radio Button always returns false

I am sending a List to the view.
Trying to submit each item in the list through a form.
Model:
public partial class Model
{
public int Id { get; set; }
public string UId { get; set; }
public int WId { get; set; }
public bool IsEnabled { get; set; }
public virtual AspNetUsers User { get; set; }
public virtual WModel W { get; set; }
}
Controller:
public IActionResult UWC()
{
List<Model> uW = db.UW.Include(x => x.U).Include(x=>x.W).ToList();
return View(uW);
}
[HttpPost]
public IActionResult UWC(Model uW)
{
var s = ModelState.ErrorCount;
return RedirectToAction("UWC");
}
View
#model List<Model>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model[0].W.Name)
</th>
<th>
#Html.DisplayNameFor(model => model[0].W.Type)
</th>
<th>
#Html.DisplayNameFor(model => model[0].W.Description)
</th>
<th>
#Html.DisplayNameFor(model => model[0].W.IsActive)
</th>
</tr>
</thead>
<tbody>
#for (var item = 0; item < Model.Count(); item++)
{
<tr>
<td>
#Html.DisplayFor(model => model[item].W.Name)
</td>
<td>
#Html.DisplayFor(model => model[item].W.Type)
</td>
<td>
#Html.DisplayFor(model => model[item].W.Description)
</td>
<td>
<form asp-action="UserWidgetConfiguration" asp-controller="UserManagement" method="post">
#Html.RadioButtonFor(model => model[item].IsEnabled, true, new { #Name = "IsEnabled",, id = "enabled_" + item } })<label>True</label>
#Html.RadioButtonFor(model => model[item].IsEnabled, false, new { #Name = "IsEnabled" ,, id = "disabled_" + item }})<label>False</label>
<input type="hidden" asp-for="#Model[item].Id" value="#Model[item].Id" name="Id" />
<input type="hidden" asp-for="#Model[item].WidgetId" value="#Model[item].WidgetId" name="WidgetId" />
<input type="hidden" asp-for="#Model[item].UserId" value="#Model[item].UserId" name="UserId" />
</form>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
#section Scripts{
<script>
$(function () {
$('input[type=radio]').change(function () {
$(this).closest('form').submit();
});
});
</script>
}
The above is the complete code.
The radio button is always binding to false.
However,
I am using a script to submit the form onchange of radio button value:
<script>
$(function () {
$('input[type=radio]').change(function () {
var data = JSON.stringify($(this).closest('form').serializeArray());
console.log(data);
$(this).closest('form').submit();
});
});
</script>
The console gives the proper value for the radio button.
[{"name":"[0].IsEnabled","value":"True"},{"name":"Id","value":"1"},{"name":"WId","value":"1"},{"name":"UId","value":"a"},{"name":"__RequestVerificationToken","value":"CfDJ8FLfqW1-k2hNlQsGtRBQVqOKRWmlkQYWTMrEQNcJHWGd7_LPvHfjw3V5gxYAnLjwz7HvjExZDXgmbSMQ1DnEONg7EJfu5OqYm7xntqXIe4IMkD1HD4SHRtihdyzDXHrKu7jNXUwuN1B6H-565O0J0oZsGVCopZqy180oPco29vqyvpcZkZnWEOmVQX6_V3T6AQ"}]
When I am expecting a true value for IsEnabled in the controller I am getting a false value.
But the value is true as expected when the form is serialized and displayed in the console.
Is this because of the event handler?
The array prefix in the name of the radio inputs ([0].IsEnabled) causes the inputs not to be mapped in the model, as the name is expected to be IsEnabled.
As simple workaround you could just create the inputs manually without the HTML Helpers, e.g.:
<input type="radio" name="IsEnabled" value="True"/> <label>True</label>
<input type="radio" name="IsEnabled" value="False"/> <label>False</label>
See the source of the helper for additional details.

Call Partial View on button click

I have 2 drop down lists in a Partial View and want to display 1st drop down on 1st Search click and 2nd drop down on 2nd Search click in View. The Index contains list of 2 Students Name and each student has Search button.Please guide me how to write code to display drop down based on button click condition. Any help and guidance is highly appreciated.
My Index View:
#model IEnumerable<StudentProject.StudentDetail>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.StudentName)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.StudentName)
</td>
<td>
<input type="button" class="btn btn-info" id="btnSearch" value="Search" />
#Html.ActionLink("Details", "Details", new { id=item.StudentId })
</td>
</tr>
}
</table>
<div id="searchResults">
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var url = '#Url.Action("DisplaySearchResults", "Student")';
$('#btnSearch').click(function () {
debugger;
$('#searchResults').load(url);
})
</script>
My Partial View _StudentLocation:
<!Doctype html>
<html>
<head>
Locations Details
</head>
<body>
<select class="dropdown">
<option>Auckland</option>
<option>Wellington</option>
</select>
<select class="dropdown">
<option>Hamilton</option>
<option>Christchurch</option>
</select>
</body>
</html>
My Controller:
using System.Linq;
using System.Net;
using System.Web.Mvc;
namespace StudentProject.Controllers
{
public class StudentController : Controller
{
private StudentEntities db = new StudentEntities();
// GET: Student
public ActionResult Index()
{
return View(db.StudentDetails.ToList());
}
// GET: Student/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
StudentDetail studentDetail = db.StudentDetails.Find(id);
if (studentDetail == null)
{
return HttpNotFound();
}
return View(studentDetail);
}
public ActionResult DisplaySearchResults()
{
return PartialView("_StudentLocation");
}
}
}

how to execute java code from a jsp page using a button?

this is my jsp code:
EMAIL.JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Example</title>
</head>
<body>
<form method="post" action="">
<center>
<table border="1" width="30%" cellpadding="3">
<thead>
<tr>
<th colspan="2">Enter the information</th>
</tr>
</thead>
<tbody>
<tr>
<td>To Address</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>Subject</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>AttachFile</td>
<td<inputtype="text"value=".\ogc\hb1_800.jpg"id=".\ogc\hb1_800.jpg" />
</td>
</tr>
<tr>
<td><input type="reset" value="Clear" /></td>
<td><input type="Submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</center>
</form>
and on clicking the submit button i need to execute the java code:
final.java which is below:-
FINAL.JAVA
package com.grid;
public class final {
public static void main(String[] args) {
String ToAddress = new String[]{"8789951#gmail.com"};
String Subject = "Hi this is test Mail";
String AttachFile = {".\ogc\notepad\styles\thumbs\hb1_800.jpg"};
new Email().sendMail(ToAddress,Subject,AttachFile);
}
}
it calls the email.java
package com.grid;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Email{
private String SMTP_HOST = "smtp.gmail.com";
private String FROM_ADDRESS = "n123f#gmail.com";
private String PASSWORD = *****";
private String FROM_NAME = "Abc";
public boolean sendMail(String ToAddress,String Subject,String AttachFile) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.auth", "true");
props.put("mail.debug.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
Session session = Session.getInstance(props, new SocialAuth());
MimeMessage msg = new MimeMessage(session);
InternetAddress from = new InternetAddress(FROM_ADDRESS, FROM_NAME);
msg.setFrom(from);
InternetAddress[] ToAddress = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
ToAddress = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, ToAddress);
msg.setSubject(Subject);
MimeBodyPart msgBodyPart = new MimeBodyPart();
// Fill the message
msgBodyPart.setText("This is message body");
// Create a multipart message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(msgBodyPart);
// Part two is attachment
if (FileName != null && FileName.length > 0)
{
for (String filePath : FileName)
{
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.AttachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
/*DataSource source = new FileDataSource(filename);
msgBodyPart.setDataHandler(new DataHandler(source));
msgBodyPart.setFileName(filename);
multipart.addBodyPart(msgBodyPart);*/
msg.setContent(multipart);
Transport.send(msg);
return true;
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
return false;
} catch (MessagingException ex) {
Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null,ex);
return false;
}
}
class SocialAuth extends Authenticator {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
new PasswordAuthentication(FROM_ADDRESS, PASSWORD);
}
}
}
Now my doubt is how to execute final.java (which is a running code) on clicking the button submit in email.jsp page?
Here is a simple servlet for demonstration:
JSP:
<form method="post" action="/email">
<center>
<table border="1" width="30%" cellpadding="3">
<thead>
<tr>
<th colspan="2">Enter the information</th>
</tr>
</thead>
<tbody>
<tr>
<td>To Address</td>
<td><input type="text" name="to" value="" /></td>
</tr>
<tr>
<td>Subject</td>
<td><input type="text" name="subject" value="" /></td>
</tr>
<tr>
<td>AttachFile</td>
<td> <input type="text" name="file" value=".\ogc\hb1_800.jpg"id=".\ogc\hb1_800.jpg" />
</td>
</tr>
<tr>
<td><input type="reset" value="Clear" /></td>
<td><input type="Submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</center>
</form>
Servlet:
#WebServlet(name="mytest", urlPatterns={"/email"})
public class MailServlet extends javax.servlet.http.HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String to = request.getParameter("to");
String subject = request.getParameter("subject");
String file = request.getParameter("file");
new Email().sendMail(to,subject,file);
response.getWriter().println("Email sent");
}
}

Categories

Resources