Model Binding with List of Objects Not Working - entity-framework

Model binding a List of objects is not working as expected.
When entering the OnPost method the UploadTransactions List is not null, but an empty list.
I have followed the instructions outlined here
I have been trying to figure this out for days now, I can't seem to wrap my head around why this is not working as expected.
Even some advice on how to debug what is being posted and why it is failing to bind to the property would be helpful. I can bind any other data as expected, but when I try to use a list of objects I am unable to get it to work.
public class UploadTransaction
{
public UploadTransaction()
{
}
public string Date { get; set; }
public string Amount { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public string Location { get; set; }
public string State { get; set; }
public string TransId { get; set; }
}
public class ViewUploadModel : PageModel
{
public BankscrapeDbContext BankscrapeDbContext { get; }
[BindProperty]
public List<UploadTransaction> UploadTransactions { get; set; }
public List<Transaction> Transactions { get; set; }
public ViewUploadModel(BankscrapeDbContext bankscrapeDbContext)
{
BankscrapeDbContext = bankscrapeDbContext;
}
public void OnGet()
{
Transactions = JsonConvert.DeserializeObject<List<Transaction>>(this.HttpContext.Session.GetString("UploadTransactions"));
}
public IActionResult OnPost()
{
}
}
<form method="post">
<div clss="container">
<table class="table table-striped">
<thead>
<tr>
<td>Date</td>
<td>Amount</td>
<td>Type</td>
<td>Description</td>
<td>Location</td>
<td>State</td>
<td>Transaction ID</td>
</tr>
</thead>
<tbody>
#for (var i = 0; i < Model.Transactions.Count; i++)
{
<tr>
<td><input class="form-control" type="text" aps-for="UploadTransactions[#i].Date" value="#Model.Transactions[i].Date" /></td>
<td><input class="form-control" type="text" aps-for="UploadTransactions[#i].Amount" value="#Model.Transactions[i].Amount" /></td>
<td><input class="form-control" type="text" aps-for="UploadTransactions[#i].Type" value="#Model.Transactions[i].Type" /></td>
<td><input class="form-control" type="text" aps-for="UploadTransactions[#i].Description" value="#Model.Transactions[i].Description" /></td>
<td><input class="form-control" type="text" aps-for="UploadTransactions[#i].Location" value="#Model.Transactions[i].Location" /></td>
<td><input class="form-control" type="text" aps-for="UploadTransactions[#i].State" value="#Model.Transactions[i].State" /></td>
<td><input class="form-control" type="text" aps-for="UploadTransactions[#i].TransId" value="#Model.Transactions[i].TransId" /></td>
</tr>
}
</tbody>
</table>
</div>
<div class="container">
<button class="btn btn-primary mt-3" type="submit" style="min-width:100%" id="button-submit">Upload</button>
</div>
</form>

Try to change aps-for="UploadTransactions[#i].xxx" with name="UploadTransactions[#i].xxx:
#for (var i = 0; i < Model.Transactions.Count; i++)
{
<tr>
<td><input class="form-control" type="text" name="UploadTransactions[#i].Date" value="#Model.Transactions[i].Date" /></td>
<td><input class="form-control" type="text" name="UploadTransactions[#i].Amount" value="#Model.Transactions[i].Amount" /></td>
<td><input class="form-control" type="text" name="UploadTransactions[#i].Type" value="#Model.Transactions[i].Type" /></td>
<td><input class="form-control" type="text" name="UploadTransactions[#i].Description" value="#Model.Transactions[i].Description" /></td>
<td><input class="form-control" type="text" name="UploadTransactions[#i].Location" value="#Model.Transactions[i].Location" /></td>
<td><input class="form-control" type="text" name="UploadTransactions[#i].State" value="#Model.Transactions[i].State" /></td>
<td><input class="form-control" type="text" name="UploadTransactions[#i].TransId" value="#Model.Transactions[i].TransId" /></td>
</tr>
}

Related

How do I pass master id to detail foreign key?

I have a master-detail edit that doesn't work as it should.
TaBarHeader - master and TaBarBody - detail, have one-to-many relationship:
public partial class TaBarHeader
{
[Key]
public int Id { get; set; }
public string ListaOtf { get; set; }
public IEnumerable<TaBarBody> TaBarBodies { get; set; }
public IEnumerable<TaBarTelegrama> TaBarTelegramas { get; set; }
}
public partial class TaBarBody
{
[Key]
public int Id { get; set; }
public string Codstatie1 { get; set; }
public int BarHeaderId { get; set; }
[ForeignKey("BarHeaderId")]
public TaBarHeader BarHeaderFk { get; set; }
}
HeaderTelegrama/Details.cshtml:
#model TraficAlert.Models.ViewModels.HeaderTelegramaViewModel
<dt class="col-sm-2">
#Html.DisplayNameFor(model => model.TaBarHeader.ListaOtf)
</dt>
<dd class="col-sm-10">
#Html.DisplayFor(model => model.TaBarHeader.ListaOtf)
</dd>
(...)
<th>
#Html.DisplayNameFor(model => model.TaBarBody.Codstatie1)
</th>
#foreach (var item in Model.TaBarHeader.TaBarBodies)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Codstatie1)
</td>
<a asp-controller="BodyTelegrama" asp-action="Edit" asp-route-id="#item.Id">Edit</a>
BodyTelegrama/Edit.cshtml:
#model TraficAlert.Models.ViewModels.BodyTelegramaViewModel
#{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>TaBarBody</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.Codstatie1" class="control-label">Cod Statie 1</label>
<input asp-for="#Model.TaBarBody.Codstatie1" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.Codstatie1" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.Codstatie2" class="control-label">Cod Statie 2</label>
<input asp-for="#Model.TaBarBody.Codstatie2" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.Codstatie2" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.DtIniP" class="control-label">Data Ini P</label>
<input asp-for="#Model.TaBarBody.DtIniP" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.DtIniP" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.DtFinP" class="control-label">Data Fin P</label>
<input asp-for="#Model.TaBarBody.DtFinP" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.DtFinP" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.DtIniR" class="control-label">Data Ini R</label>
<input asp-for="#Model.TaBarBody.DtIniR" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.DtFinP" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.DtFinR" class="control-label">Data Fin R</label>
<input asp-for="#Model.TaBarBody.DtFinR" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.DtFinR" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.KmIni" class="control-label">Km Ini</label>
<input asp-for="#Model.TaBarBody.KmIni" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.KmIni" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.KmFin" class="control-label">Km Fin</label>
<input asp-for="#Model.TaBarBody.KmFin" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.KmFin" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.LiniaFir" class="control-label">Linia Fir</label>
<input asp-for="#Model.TaBarBody.LiniaFir" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.LiniaFir" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.NomImpactId" class="control-label">Impact</label>
<select asp-for="#Model.TaBarBody.NomImpactId" class="form-control" asp-items="ViewBag.NomImpactId"></select>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.NomAnulatId" class="control-label">Anulat</label>
<select asp-for="#Model.TaBarBody.NomAnulatId" class="form-control" asp-items="ViewBag.NomAnulatId"></select>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.MotivAnulare" class="control-label">Motiv Anulare</label>
<input asp-for="#Model.TaBarBody.MotivAnulare" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.MotivAnulare" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.TaBarBody.Ruta" class="control-label">Ruta</label>
<input asp-for="#Model.TaBarBody.Ruta" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.Ruta" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" asp-route-id="#ViewBag.TelegramaId" value="Save" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
BodyTelegramaController:
// GET
public IActionResult Edit(int id, int HeaderTelegramaId)
{
BodyTelegramaViewModel bodyTelegramaViewModel = new BodyTelegramaViewModel();
bodyTelegramaViewModel.TaBarBody = new TaBarBody();
bodyTelegramaViewModel.TaBarBody.BarHeaderFk = new TaBarHeader();
bodyTelegramaViewModel.TaBarBody = _unitofwork.BarBody.DetailsBarB(id);
bodyTelegramaViewModel.TaBarBody.BarHeaderFk = _unitofwork.BarHeader.DetailsBarHB(id);
ViewData["TelegramaId"] = HeaderTelegramaId;
if (bodyTelegramaViewModel.TaBarBody == null)
{
return NotFound();
}
ViewData["NomImpactId"] = new SelectList(_unitofwork.NomImpact.GetAll(), "Id", "Nume");
ViewData["NomAnulatId"] = new SelectList(_unitofwork.NomAnulat.GetAll(), "Id", "Nume");
return View(bodyTelegramaViewModel);
}
// POST
public IActionResult Edit(int id, BodyTelegramaViewModel bodyTelegramaViewModel)
{
if (id != bodyTelegramaViewModel.TaBarBody.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
bodyTelegramaViewModel.TaBarBody.BarHeaderId = id;
_unitofwork.BarBody.Update(bodyTelegramaViewModel.TaBarBody);
_unitofwork.Save();
}
catch (DbUpdateConcurrencyException)
{
if (!TaBarBodyExists(bodyTelegramaViewModel.TaBarBody.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(bodyTelegramaViewModel);
}
Everytime I edit a record, my foreign key - BarHeaderId - change its value to 0.
I have tried bodyTelegramaViewModel.TaBarBody.BarHeaderId = bodyTelegramaViewModel.TaBarHeader.Id; but I get the error 'Object reference not set to an instance of an object.'
How can I get the TaBarHeader.Id value and put it in TaBarBody.BarHeaderId?
Update:
ViewModels:
public class HeaderTelegramaViewModel
{
public TaBarHeader TaBarHeader { get; set; }
public IEnumerable<TaBarHeader> taBarHeader { get; set; }
public TaBarBody TaBarBody { get; set; }
public IEnumerable<TaBarBody> taBarBody { get; set; }
}
public class BodyTelegramaViewModel
{
public TaBarBody TaBarBody { get; set; }
public IEnumerable<TaBarBody> taBarBody { get; set; }
}
HeaderTelegramaController:
public IActionResult Details(int id)
{
HeaderTelegramaViewModel headerTelegramaViewModel = new HeaderTelegramaViewModel();
headerTelegramaViewModel.TaBarHeader = _unitofwork.BarHeaderRepository.DetailsBarHB(id);
if (headerTelegramaViewModel == null)
{
return NotFound();
}
return View(headerTelegramaViewModel);
}
BodyTelegramaController:
// GET
public IActionResult Edit(int id)
{
BodyTelegramaViewModel bodyTelegramaViewModel = new BodyTelegramaViewModel();
bodyTelegramaViewModel.TaBarBody = new TaBarBody();
bodyTelegramaViewModel.TaBarBody.BarHeaderFk = new TaBarHeader();
bodyTelegramaViewModel.TaBarBody = _unitofwork.BarBodyRepository.DetailsBarB(id);
bodyTelegramaViewModel.TaBarBody.BarHeaderFk = _unitofwork.BarHeaderRepository.DetailsBarHB(id);
return View(bodyTelegramaViewModel);
}
These are the methods DetailsBarB() and DetailsBarHB():
public TaBarBody DetailsBarB(int id)
{
return _db.TaBarBodies
.Include(t => t.BarHeaderFk)
.FirstOrDefault(m => m.Id == id);
}
public TaBarHeader DetailsBarHB(int id)
{
return _db.TaBarHeaders
.Include(x => x.TaBarBodies).ThenInclude(x => x.BarHeaderFk.CategoriaFk)
.FirstOrDefault(m => m.Id == id);
}
You can do following changes to get the TaBarHeader id.
In your Details View,change it to:
<a asp-controller="BodyTelegrama" asp-action="Edit" asp-route-id="#item.Id" asp-route-HeaderTelegramaId="#Model.TaBarHeader.Id">Edit</a>
In your Edit action,change it to:
public IActionResult Edit(int id,int HeaderTelegramaId)
{
BodyTelegramaViewModel bodyTelegramaViewModel = new BodyTelegramaViewModel();
bodyTelegramaViewModel.TaBarBody = new TaBarBody();
bodyTelegramaViewModel.TaBarBody.BarHeaderFk = new TaBarHeader();
bodyTelegramaViewModel.TaBarBody = _unitofwork.BarBodyRepository.DetailsBarB(id);
bodyTelegramaViewModel.TaBarBody.BarHeaderFk = _unitofwork.BarHeaderRepository.DetailsBarHB(id);
ViewData["TelegramaId"] = HeaderTelegramaId;
return View(bodyTelegramaViewModel);
}
[HttpPost]
public IActionResult Edit(int id, BodyTelegramaViewModel bodyTelegramaViewModel)
{
bodyTelegramaViewModel.TaBarBody.BarHeaderId = id;
_unitofwork.BarBodyRepository.Update(bodyTelegramaViewModel.TaBarBody);
_unitofwork.Save();
return View(bodyTelegramaViewModel);
}
Then in your Edit View,change it to:
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<input type="hidden" asp-for="#Model.TaBarBody.Id" />
<label asp-for="#Model.TaBarBody.Codstatie1" class="control-label">Cod Statie 1</label>
<input asp-for="#Model.TaBarBody.Codstatie1" class="form-control" />
<span asp-validation-for="#Model.TaBarBody.Codstatie1" class="text-danger"></span>
</div>
<div>
<input type="submit" asp-route-id="#ViewBag.TelegramaId" value="Save"/>
</div>
</form>
Then in your Edit post action,the id will be the TaBarHeader.Id.
Test Result:

Set value Entity Framework Core during OnGet

I thought this would be simple...
If I want to force a value to a column/filed before the page loads, how do I do that?
Here's the lines from the Model:
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name = "Contract Value")]
public decimal? ContractValue { get; set; } = 0m;
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name = "Contract Expended")]
public decimal? ContractValueExpended { get; set; } = 0m;
And, here's what I tried using Fluent API.
modelBuilder.Entity<Contract>()
.Property(e => e.ContractValue)
.HasDefaultValue(0);
modelBuilder.Entity<Contract>()
.Property(e => e.ContractValueExpended)
.HasDefaultValue(0);
My bad. Here is create.cshtml.cs
public class CreateModel : GlobalPageModel
{
private readonly TawdryIndustries.Data.CompanyContext _context;
public CreateModel(TawdryIndustries.Data.CompanyContext context)
{
_context = context;
}
public IActionResult OnGet()
{
PopulateEmployeeNamesSelectList(_context);
PopulateCustomerNamesSelectList(_context);
return Page();
}
[BindProperty]
public Contract Contract { get; set; }
public async Task<IActionResult> OnPostAsync()
{
var emptyContract = new Contract();
if (await TryUpdateModelAsync<Contract>(
emptyContract,
"Contract",
c => c.ContractID,
c => c.ContractNumber,
c => c.ContractName,
c => c.CustomerID,
c => c.ContractAwardDate,
c => c.ContractBegDate,
c => c.ContractEndDate,
c => c.ContractValue,
c => c.ContractValueExpended,
c => c.ContractManagerID))
{
_context.Contracts.Add(emptyContract);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
PopulateEmployeeNamesSelectList(_context, emptyContract.ContractManagerID);
PopulateCustomerNamesSelectList(_context, emptyContract.CustomerID);
return Page();
}
And, here is the razor page (create.cshtml):
#page
#model TawdryIndustries.Pages.Contracts.CreateModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Contract</h4>
<hr />
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<table class="table">
<tr>
<td>
<label asp-for="Contract.CustomerID" class="control-label"></label>
<select asp-for="Contract.CustomerID" class="form-control"
asp-items="#Model.CustomerNameSL">
<option value="">-- Select Customer --</option>
</select>
<span asp-validation-for="Contract.CustomerID" class="text-danger"></span>
</td>
<td>
<label asp-for="Contract.ContractNumber" class="control-label"></label>
<input asp-for="Contract.ContractNumber" class="form-control" />
<span asp-validation-for="Contract.ContractNumber" class="text-danger"></span>
</td>
<td>
<label asp-for="Contract.ContractName" class="control-label"></label>
<input asp-for="Contract.ContractName" class="form-control" />
<span asp-validation-for="Contract.ContractName" class="text-danger"></span>
</td>
</tr>
<tr>
<td>
<label asp-for="Contract.ContractAwardDate" class="control-label"></label>
<input asp-for="Contract.ContractAwardDate" class="form-control" />
<span asp-validation-for="Contract.ContractAwardDate" class="text-danger"></span>
</td>
<td>
<label asp-for="Contract.ContractBegDate" class="control-label"></label>
<input asp-for="Contract.ContractBegDate" class="form-control" />
<span asp-validation-for="Contract.ContractBegDate" class="text-danger"></span>
</td>
<td>
<label asp-for="Contract.ContractEndDate" class="control-label"></label>
<input asp-for="Contract.ContractEndDate" class="form-control" />
<span asp-validation-for="Contract.ContractEndDate" class="text-danger"></span>
</td>
</tr>
<tr>
<td>
<label asp-for="Contract.ContractValue" class="control-label"></label>
<input asp-for="Contract.ContractValue" class="form-control" />
<span asp-validation-for="Contract.ContractValue" class="text-danger"></span>
</td>
<td>
<label asp-for="Contract.ContractValueExpended" class="control-label"></label>
<input asp-for="Contract.ContractValueExpended" class="form-control" />
<span asp-validation-for="Contract.ContractValueExpended" class="text-danger"></span>
</td>
<td>
<label asp-for="Contract.ContractManagerID" class="control-label"></label>
<select asp-for="Contract.ContractManagerID" class="form-control"
asp-items="#Model.EmployeeNameSL">
<option value="">-- Select Manager --</option>
</select>
<span asp-validation-for="Contract.ContractManagerID" class="text-danger"></span>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Create" class="btn btn-primary" />
</td>
</tr>
</table>
</form>
<div>
<a asp-page="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
However, when the page is displayed (in create specifically), both of those fields are still blank. I want to force both fields to 0 when a new contract is created before the page loads.
For that matter, is there any way to set a value for a variable before a page loads?
In ASP.NET I would
<html>
<head></head>
<body>
<asp:textbox id="mytext" runat="server"></asp:textbox>
</body>
and:
protected void Page_Load(object sender, EventArgs e)
{
string somevar = "This is a test";
mytext.Text = somevar;
}
And the text box would contain "This is a test" when the page was displayed.
What is the equivalent in EF Core?
Thanks,
John

Spring form model attribute class with another object

I work with Spring MVC and JSP. I want to input the class product using a form. Class Product has another object Catalog
Product class
public class Product {
private int productId;
private Catalog catalog;
private String sku;
private String productName;
private int availableQuantity;
private String uom;
public Product() {
}
Catalog is
public class Catalog {
protected static Logger logger = Logger.getLogger(Catalog.class.getName());
private int catalogId;
private String catalogName;
private List<Product> products= new ArrayList<Product>();
public Catalog() {
}
I created a modelAttribute product in the controller
model.addAttribute(new Product());
return "product/addProduct";
I want to input the catalog id using a dropdown. This dropdown is
<tr>
<th><label for="catalog_id">Catalog id:</label></th>
<td><sf:select path="catalog" items="${catalogList}" />
</td>
</tr>
The jsp is:
<sf:form method="POST" modelAttribute="product">
<table border="0">
<tr>
<th><label for="catalog_id">Catalog id:</label></th>
<td><sf:select path="catalog" items="${catalogList}" />
</td>
</tr>
<tr>
<th><label for="product_name">Product Name:</label></th>
<td><sf:input path="productName" size="128" id="product_name" /><br/>
<sf:errors path="productName" cssClass="error" />
</td>
</tr>
<tr>
<th><label for="product_sku">Product sku:</label></th>
<td><sf:input path="sku" size="32" id="product_sku" /><br/>
<sf:errors path="sku" cssClass="error" />
</td>
</tr>
<tr>
<th><label for="product_availablequantity">Available Quantity:</label></th>
<td><sf:input path="availableQuantity" id="product_availablequantity" /><br/>
<sf:errors path="availableQuantity" cssClass="error" />
</td>
</tr>
<tr>
<th><label for="product_unitofmeasure">Unit of measure:</label></th>
<td><sf:input path="uom" size="32" id="product_unitofmeasure" /><br/>
<sf:errors path="uom" cssClass="error" />
</td>
</tr>
<tr>
<th></th>
<td><input type="submit" value="Save" /></td>
</tr>
</table>
</sf:form>
</body>
</html>
How do I have to define the path product.catalog.catalogId?

return new ModelAndView redirect does not work for some reason

I'm really new to Spring MVC framework and I'm in desperate need of help right now.
For some reason, my redirect does not work its giving me HTTP Status 400, with no error on console that is why it is very hard to debug.
Scenario:
I have 2 forms. The first form is saving properly then redirects to 2nd form, but when I repeat my code to pass it to the 3rd form I get an http 400 error. I'm pretty sure I replicated what I used on the first form.
View:
<form:form method="POST" commandName="kiosk"
action="${pageContext.request.contextPath}/kiosk/kiosk-initial-info-save.html">
<div align="center">
<br />
<div id="addKioskContainer">
<div class="datagrid1" align="center" style="width: 33%;">
<table align="center">
<thead>
<tr>
<th colspan="4" style="text-align: left;">Initial Information</th>
</tr>
</thead>
</table>
</div>
<div>
<table>
<tr>
<td>
<h3 align="left"> You are applying for <label style="color: blue;">Restructured Loan</label> in <label style="color: blue;">Eastwood.</label></h3>
</td>
</tr>
</table>
</div>
<div id="initialInfoContainer">
<table cellpadding="0" cellspacing="10">
<tr>
<td style="font-size: 12px;" >
<b>Purpose of Loan: </b>
</td>
<td>
<form:input path="loanPurpose" size="40"></form:input>
</td>
</tr>
</table>
</div>
<br />
<div id="applicantInfoContainer">
<div class="datagrid2" align="center" style="width: 95%;">
<table align="center">
<thead>
<tr>
<th colspan="4" style="text-align: left;">Applicant's Information</th>
</tr>
</thead>
<tr>
<td style="font-size: 12px;" >
<b>Last Name: </b><label style="color: red;">*</label>
</td>
<td>
<form:input path="appLastName" size="40"></form:input>
</td>
</tr>
<tr>
<td style="font-size: 12px;" >
<b>First Name: </b><label style="color: red;">*</label>
</td>
<td>
<form:input path="appFirstName" size="40"></form:input>
</td>
</tr>
<tr>
<td style="font-size: 12px;" >
<b>Middle Name: </b><label style="color: red;">*</label>
</td>
<td>
<form:input path="appMiddleName" size="40"></form:input>
</td>
</tr>
<tr>
<td style="font-size: 12px;" >
<b>Birthdate: </b><label style="color: red;">*</label>
</td>
<td>
<form:input path="appBirthDate" size="20"></form:input>
</td>
</tr>
<tr>
<td style="font-size: 12px;" >
<b>w/ Comaker: </b><label style="color: red;">*</label>
</td>
<td>
<form:checkbox path="withCoMaker"></form:checkbox>
</td>
</tr>
</table>
</div>
</div>
<br />
<div id="comakerInfoContainer">
<div class="datagrid2" align="center" style="width: 95%;">
<table align="center">
<thead>
<tr>
<th colspan="4" style="text-align: left;">Comaker's Information</th>
</tr>
</thead>
<tr>
<td style="font-size: 12px;" >
<b>Last Name: </b><label style="color: red;">*</label>
</td>
<td>
<form:input path="comakerLastName" size="40"></form:input>
</td>
</tr>
<tr>
<td style="font-size: 12px;" >
<b>First Name: </b><label style="color: red;">*</label>
</td>
<td>
<form:input path="comakerFirstName" size="40"></form:input>
</td>
</tr>
<tr>
<td style="font-size: 12px;" >
<b>Middle Name: </b><label style="color: red;">*</label>
</td>
<td>
<form:input path="comakerMiddleName" size="40"></form:input>
</td>
</tr>
<tr>
<td style="font-size: 12px;" >
<b>Birthdate: </b><label style="color: red;">*</label>
</td>
<td>
<form:input path="comakerBirthDate" size="20"></form:input>
</td>
</tr>
</table>
</div>
</div>
<br />
<div align="center">
<table>
<tr>
<td align="center"><input type="submit" value="Next" id="btnProceedKiosk"/></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
Controller:
#RequestMapping( value = "/kiosk-initial-info", method = RequestMethod.GET )
public ModelAndView initialInfoKioskPage()
{
ModelAndView modelAndView = new ModelAndView( "kiosk-initial-info" );
modelAndView.addObject( "kiosk", new Kiosk() );
return modelAndView;
}
#RequestMapping( value = "/kiosk-initial-info-save", method = RequestMethod.POST )
public ModelAndView saveInitialInfo( #ModelAttribute
Kiosk kiosk )
{
ModelAndView modelAndView = new ModelAndView( "kiosk-initial-info" );
modelAndView.addObject( "kiosk", new Kiosk() );
return new ModelAndView( "redirect:/kiosk/kiosk-initial-info.html" );
}
Model:
package com.etel.kiosk.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table( name = "kioskmain" )
public class Kiosk
{
#Id
#GeneratedValue
private Integer id;
private String loanType;
private String branch;
private String loanPurpose;
private String appLastName;
private String appFirstName;
private String appMiddleName;
private Date appBirthDate;
private Boolean withCoMaker;
private String comakerLastName;
private String comakerFirstName;
private String comakerMiddleName;
private Date comakerBirthDate;
public Integer getId()
{
return id;
}
public void setId( Integer id )
{
this.id = id;
}
public String getLoanType()
{
return loanType;
}
public void setLoanType( String loanType )
{
this.loanType = loanType;
}
public String getBranch()
{
return branch;
}
public void setBranch( String branch )
{
this.branch = branch;
}
public String getLoanPurpose()
{
return loanPurpose;
}
public void setLoanPurpose( String loanPurpose )
{
this.loanPurpose = loanPurpose;
}
public String getAppLastName()
{
return appLastName;
}
public void setAppLastName( String appLastName )
{
this.appLastName = appLastName;
}
public String getAppFirstName()
{
return appFirstName;
}
public void setAppFirstName( String appFirstName )
{
this.appFirstName = appFirstName;
}
public String getAppMiddleName()
{
return appMiddleName;
}
public void setAppMiddleName( String appMiddleName )
{
this.appMiddleName = appMiddleName;
}
public Date getAppBirthDate()
{
return appBirthDate;
}
public void setAppBirthDate( Date appBirthDate )
{
this.appBirthDate = appBirthDate;
}
public Boolean getWithCoMaker()
{
return withCoMaker;
}
public void setWithCoMaker( Boolean withCoMaker )
{
this.withCoMaker = withCoMaker;
}
public String getComakerLastName()
{
return comakerLastName;
}
public void setComakerLastName( String comakerLastName )
{
this.comakerLastName = comakerLastName;
}
public String getComakerFirstName()
{
return comakerFirstName;
}
public void setComakerFirstName( String comakerFirstName )
{
this.comakerFirstName = comakerFirstName;
}
public String getComakerMiddleName()
{
return comakerMiddleName;
}
public void setComakerMiddleName( String comakerMiddleName )
{
this.comakerMiddleName = comakerMiddleName;
}
public Date getComakerBirthDate()
{
return comakerBirthDate;
}
public void setComakerBirthDate( Date comakerBirthDate )
{
this.comakerBirthDate = comakerBirthDate;
}
}
DaoImpl
public void updateKiosk( Kiosk kiosk )
{
Kiosk kioskToUpdate = getKiosk( kiosk.getId() );
kioskToUpdate.setBranch( kiosk.getBranch() );
kioskToUpdate.setLoanPurpose( kiosk.getLoanPurpose() );
kioskToUpdate.setAppLastName( kiosk.getAppLastName() );
kioskToUpdate.setAppFirstName( kiosk.getAppFirstName() );
kioskToUpdate.setAppMiddleName( kiosk.getAppMiddleName() );
kioskToUpdate.setAppBirthDate( kiosk.getAppBirthDate() );
kioskToUpdate.setWithCoMaker( kiosk.getWithCoMaker() );
kioskToUpdate.setComakerLastName( kiosk.getComakerLastName() );
kioskToUpdate.setComakerFirstName( kiosk.getComakerFirstName() );
kioskToUpdate.setComakerMiddleName( kiosk.getComakerMiddleName() );
kioskToUpdate.setComakerBirthDate( kiosk.getComakerBirthDate() );
getCurrentSession().update( kioskToUpdate );
}
Your answers will be of great help. Thanks.

In Thymeleaf with multiple actions and multiple forms are possible?

Hi i am new in thymeleaf + spring and i start learn it.
and wanted to integrate these 2 form in one page .
that means now 2 forms are in 2 different pages and the th:action are different ..
here i want these 2 forms work in one page
i tried that with a page with 2 forms and 2 actions but that caught error..
Create Standard Code
<form action="#" th:action="#{/saveStandard.html}" th:object="${standard}">
<table>
<h1>Create Standard</h1>
<tr>
<td>Standard Name:</td>
<td><input type="text" placeholder="Enter Standard Name" required="required"
th:field="*{standardName}"/></td>
</tr>
<tr>
<td><input type="submit" value="Create" name="save" /></td>
</tr>
</table>
</form>
Create Division Code
<form action="#" th:action="#{/saveDivision.html}"
th:object="${division}">
<table>
<td>Division Name:</td>
<tr>
<td><input type="text" placeholder="Enter Division Name" required="required"
th:field="*{divisionName}" />
</td>
</tr>
<td><input type="submit" class="btn btn-primary" value="Create"
name="save" /></td>
</table>
</form>
these are controllers..
#RequestMapping(value = Array("/saveStandard.html"), params = Array({ "save" }))
def saveStandard(standard: Standard): String = {
standard.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
standardService.addStandard(standard)
"redirect:/school/CreateStandard.html"
}
#RequestMapping(value = Array("/saveDivision.html"), params = Array({ "save" }))
def saveDivision(division: Division): String = {
division.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
divisionService.addDivision(division)
"redirect:/school/CreateDivision.html"
}
if you knew about this question please share your answer here..
and Thanks...
Hi It is posible here a example
HTML Example
<section id="registration" class="section">
<div class="container tagline">
<em>Register User</em><br />
<form method="post" th:action="#{/user/register}" th:object="${newUser}">
<div>
<label for="givenName">Id</label>
<input id="id" placeholder="Enter Id" type="text" th:field="*{id}" />
<p th:if="${#fields.hasErrors('id')}" th:text="${#strings.listJoin(#fields.errors('id'), ', ')}">
</p>
</div>
<div>
<label for="givenName">Name</label>
<input id="name" placeholder="Enter Name" type="text" th:field="*{name}" />
<p th:if="${#fields.hasErrors('name')}"
th:text="${#strings.listJoin(#fields.errors('name'), ', ')}"></p>
</div>
<div>
<label for="email">Email</label>
<input id="email" placeholder="Enter the Email" type="text" th:field="*{email}" />
<p th:if="${#fields.hasErrors('email')}"
th:text="${#strings.listJoin(#fields.errors('email'), ', ')}"></p>
</div>
<button type="submit">Create user</button>
</form>
</div>
</section>
<div>
<form method="get" th:action="#{/user/searchById}" th:object="${searchUser}">
<input id="id" placeholder="Search by id" type="text" th:field="*{id}" size="10" >
<button type="submit" >search</button>
</form>
<form method="get" th:action="#{/user/searchByName}" th:object="${searchUser}">
<input id="id" placeholder="Search by Name" type="text" th:field="*{name}" size="10" >
<button type="submit" >search</button>
</form>
<form method="get" th:action="#{/user/searchByEmail}" th:object="${searchUser}">
<input id="id" placeholder="Search by Email" type="text" th:field="*{email}" size="10" >
<button type="submit" >search</button>
</form>
</div>
Spring
#Controller
#RequestMapping("/user")
public class User {
BookingFacadeUserImp userService = new BookingFacadeUserImp();
#GetMapping()
public ModelAndView init() {
return getModelView().addObject("users", getUsersByName("", 100, 0));
}
#PostMapping("/register")
public ModelAndView saveUser(#Valid #ModelAttribute("newUser") UserDTO user, BindingResult result)
throws NumberFormatException, ParseException {
System.out.println("Register: " + user);
userService.createUser(user);
return getModelView().addObject("users", getUsersByName("", 100, 0));
}
#GetMapping("/delete/{id}")
public ModelAndView delete(#PathVariable long id) {
userService.deleteUser(id);
return init();
}
#PostMapping("/update")
public ModelAndView updateUser(#ModelAttribute("updateUser") UserDTO user) {
userService.updateUser(user);
return init();
}
#GetMapping("/searchById")
public ModelAndView searchById(#ModelAttribute("searchUser") UserDTO user) {
if (user.getId() > 0)
return getModelView().addObject("users", getUsersById(user.getId()));
else
return init();
}
#GetMapping("/searchByName")
public ModelAndView searchByName(#ModelAttribute("searchUser") UserDTO user) {
if (!user.getName().equals(""))
return getModelView().addObject("users", getUsersByName(user.getName(),100,0));
else
return init();
}
public ModelAndView getModelView() {
ModelAndView model = new ModelAndView("user");
model.addObject("newUser", new UserDTO());
model.addObject("searchUser", new UserDTO());
return model;
}
public List<UserDTO> getUsersById(long id) {
List<UserDTO> list = new ArrayList<UserDTO>();
list.add((UserDTO) userService.getUserById(id));
return list;
}
public List<com.example.demo.task1.model.User> getUsersByName(String name, int pageSiza, int pageNum) {
return userService.getUsersByName(name, pageSiza, pageNum);
}
public List<com.example.demo.task1.model.User> getUsersByEmail(String email) {
return (List<com.example.demo.task1.model.User>) userService.getUserByEmail(email);
}
}