How to submit an exisitng object from the view via a from in Thymeleaf with Spring MVC? - spring-mvc

In my Thymeleaf view, I have some objects shown on the page:
Here's the HTML
<form method="post" action="#" th:action="#{/basket}" th:object="${itemOrder}">
<div class="card-body">
<h4 class="card-title">
item title
</h4>
<h5 th:text="${item.price} + ' €'">item price</h5>
<input type="hidden" th:field="*{sku}"/> <br>
<input type="submit" value="Add to basket" />
</div>
</form>
<div class="container" th:if="${itemOrder != null}">
<h4>Item in the basket:</h4><br>
<h5 th:text="${itemOrder.price} + ' €'">item price</h5>
</div>
Under each element, I have a form to submit this element to the controller.
All Thymeleaf and Spring MVC guides are showing how to submit a form when a user provides data through input fields. Here, I don't need to take in any data from the user, all the data is available already. I just need to wrap existing data and submit it with a form. How can I make it with Thymeleaf and Spring MVC?
Here's the BasketController that should handle the form reu
#PostMapping("/basket")
public String processItemOrder(#ModelAttribute ItemOrder itemOrder, Model model) {
model.addAttribute("itemOrder", itemOrder);
return "basket";
}

Related

How can I send list from view to controller (ASP.NET MVC)?

I want to make export file using
ActionResult Download(List<UserProjectPercentReportViewModel> percentsByProjectsAndUsers)
method. But I can not pass a parameter. I try to send it like this:
<div class="col-md-2">
<p> </p>
<p><input type="button" onclick="location.href='#Url.Action("Download",new { percentsByProjectsAndUsers=Model})'"
class="btn btn-info" value="Export" /></p>
</div>
But I get percentsByProjectsAndUsers.Count() == 0 in my method.
When I tried to send just string, it works, but I need to pass a List<>.

Send list object from thymeleaf to controller

I have a big problem about saving an Object list from Thymeleaf to the controller. Object List in thymeleaf is generated by Jquery. but I don't know how to get the data to Controller, that Object list doesn't know the size. Because users can add it anytime.
Please help me to send a list object in thymeleaf to controller.
I’ve Created a new class with 1 properties: ArrayList loaiDoans;
"LoaiDoan" is a Object that i want to save.
And using that class is an object to Save List "LoaiDoan" from thymeleaf to controller.
But List don't know the size first.because that genarated in thymeleaf. The first time i load the Model, the Model contain List is empty,so that list is not display in screen.
This is my class
public class ListLoaiDoan {
private ArrayList<LoaiDoan> loaiDoans;
//Getter Setter
}
My controller bind list object from controller to thymeleaf
#RequestMapping("/luunhieuobject")
public String LoadNhieuObjectCungLuc(Model model) {
ListLoaiDoan listLoaiDoanAAA = new ListLoaiDoan();
model.addAttribute("listLoaiDoan111",listLoaiDoanAAA);
return "/MHtrangchu/LuuNhieuObjCungLuc";
}
//This is the method save list Object from thymeleaf to controller
#PostMapping("/luunhieuobject")
public String processQuery(#ModelAttribute("listLoaiDoan111") ListLoaiDoan listLoaiDoan) {
System.out.println(listLoaiDoan.getLoaiDoans() != null ? listLoaiDoan.getLoaiDoans().size() : "List Empty");
System.out.println("--");
return "/MHtrangchu/LuuNhieuObjCungLuc";
}
LuuNhieuObjCungLuc.html
<form th:object="${listLoaiDoan111}" method="post" th:action="#{/luunhieuobject}">
<!--INPUT FIELDS-->
<div class="row">
<div class="col">
<div id="movieList">
<div class="row">
<div style="margin-left:100px;" class="col-4 form-group">tenloaidoan</div>
<div style="margin-left:100px;" class="col-4 form-group">madoan</div>
</div>
<div class="row item" th:each="row, stat : ${listLoaiDoan111.loaiDoans}">
<div class="col-lg-6 form-group">
<input th:field="*{loaiDoans[__${stat.index}__].tenloaidoan}" type="text" class="form-control"/>
</div>
<div class="col-lg-6 form-group">
<input th:field="*{loaiDoans[__${stat.index}__].madoan}" type="text" class="form-control"/>
</div>
</div>
</div>
</div>
</div>
<!--ADD NEW ROW BUTTON-->
<div class="row">
<div class="col">
<button type="button" class="btn btn-success" onclick="addRow()">Add row</button>
</div>
</div>
<!--SUBMIT FORM BUTTON-->
<div class="row text-right">
<div class="col">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
That not display annything in the screen, i know that because "listLoaiDoanAAA" is the empty and "th:each" in thymeleaf have nothing to show, how to generate "input" tag and save to controller help me !
I solved this problem !
Set a size for ArrayList before bind it to thymeleaf !
I save my day. thanks Stackoverflow.
i fix my controller like this
#GetMapping("/luunhieuobject")
public String LoadNhieuObjectCungLuc(Model model) {
ListLoaiDoan listLoaiDoanAAA = new ListLoaiDoan();
ArrayList<LoaiDoan> LDD = new ArrayList<LoaiDoan>(10);
listLoaiDoanAAA.setLoaiDoans(LDD);
model.addAttribute("listLoaiDoan111", listLoaiDoanAAA);
return "/MHtrangchu/LuuNhieuObjCungLuc";
}

Cannot upload an image

I'm trying to update an image to my database, I defined as property model (bounded by database) the following:
public byte[] AvatarImage { get; set; }
then I created another property which store the value in the ViewModel:
public IFormFile AvatarImage { get; set; }
this steps are also described here in the doc.
Iside my form, I added the following html:
<div class="form-group text-center col-lg-12">
<img src="#Model.AvatarImage" class="avatar img-circle" alt="avatar" />
<h6>#Localizer["UploadNewAvatar"] ...</h6>
<input type="file" class="form-control" id="avatarUrl" asp-for="#Model.AvatarImages" />
</div>
when I submit the form the property AvatarImage is even null. But I don't understand why happen this, because all the other form properties are valorized correctly
Sounds like you are missing the form enctype.
Make sure you have:
<form enctype="multipart/form-data">
... inputs
<form>
Your <input type="file"> element assignment below seems to be wrong, because it uses #Model directive which outputs value of AvatarImages property (and the property is not exist in viewmodel class):
<input type="file" class="form-control" id="avatarUrl" asp-for="#Model.AvatarImages" />
The correct way is just using the property name like example below, because asp-for="PropertyName" is equivalent to model => model.PropertyName in HTML helper (assumed you have #model directive set to a viewmodel class):
<input type="file" class="form-control" asp-for="AvatarImage" />
Also don't forget to specify enctype="multipart/form-data" attribute in <form> tag helper:
<form asp-controller="ControllerName" asp-action="ActionName" method="post" enctype="multipart/form-data">
<!-- form contents here -->
</form>
Reference: Tag Helpers in forms in ASP.NET Core
First add enctype="multipart/form-data" to form ;
Then,check your #model, two situations :
1.Use Model directly, since the image is a byte array type, you need to convert the file type to byte[] during the submission process.
2.Or you could use ViewModel, and change the parameter type to viewmodel in the method.

Spring MCV 3 showErrors doesn't display anything

I try to validate a simple form. The validation is well executed but the result page doesn't display the errors.
I use velocity to render the page.
I've used as example the PetClinic project from spring website.
Here is my controller when I hit the "post form" button:
#Controller
#RequestMapping("/subscription")
public class SubscriptionController {
#RequestMapping(value = "/newCustomer", method = RequestMethod.POST)
public String processSubmit(#ModelAttribute Customer customer, BindingResult result, SessionStatus status) {
new CustomerValidator().validate(customer, result);
if (result.hasErrors()) {
return "subscription";
}
else {
status.setComplete();
return "redirect:/admin";
}
}
}
When I go in debug, I see the errors. I'm successfully redirected on the subscription page but the errors are not displayed.
My webpage (simplified):
...
#springBind("customer")
#springShowErrors("<br/>" "")
<form class="form-horizontal" method="post" action="#springUrl("/subscription/newCustomer/")">
....
<!-- Button -->
<div class="controls">
<button class="btn btn-primary">#springMessage("website.subscription.signup")</button>
</div>
</form>
...
if you need anything else, don't hesitate to tell me. Thanks for your help! I'm stuck on this since several days.
EDIT :
I finally found the error. It was with the springBind tag. I didn't well understand that you need to bind the field to show the associated error. Here is the fixed code for one field for twitter bootstrap framework.
#springBind("customer.name")
<div class="control-group #if(${status.error})error#end">
<!-- Prepended text-->
<label class="control-label">#springMessage("website.subscription.name")</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input class="input-xlarge"
placeholder="John Doe" id="name" name="name" type="text">
</div>
<p class="help-block">
#springShowErrors("<br/>" "")
</p>
</div>
</div>
springShowErrors(...) will show all the errors associated with the field name of the POJO customer.

ASP.NET MVC 3: HTTP Post parameter allways null after deployment

I've created a small website in ASP.NET MVC 3, and it works fine in debugenvironment.
After deployment (on a https website) the website gives problems and after figuring a while, it seems that the HTTPPOST parameters are allways null ...
I'll provide some information:
the .cshtml:
#using (#Html.BeginForm("Registration", "Home", FormMethod.Post)){
<div id="middle">
<div id="radio">
#foreach (var item in Model)
{
<input type="radio" id="#string.Format("radio{0}", item.ID)" name="radio" value="#item.ID" /><label for="#string.Format("radio{0}", item.ID)">#item.Description</label>
}
</div>
<div id="divOverig">
<label for="overig">
Overig:</label>
<input style="float:right; width:70%;" type="text" id="overig" name="overig" />
</div>
</div>
<div id="end">
</div>
<div id="left">
#Html.ActionLink("Terug", "Device")
</div>
<div id="right">
<input type="submit" id="next" value="Naar apparaat informatie" />
</div>
}
The controller:
public ActionResult Problem(string radio, string overig){ ... }
In debug environment the parameters are correctly filled and passed. On the webserver the parameter is allways empty.
When I change the POST in GET is works fine, but I want to use the POST (later in the website I use complex types).
Anyone a brilliant idea?
This problem is caused by the secure environment (https).
I put the website on a normal environment (http) and it works flawless ;)
Thanx for you're time.
decorate the ActionResult with HttpPost
[HttpPost]
public ActionResult Registration(string radio, string overig){ ... }

Resources