How to upload more than 1 image in database in asp.net core mvc using ado.net - insert

I create a form where i insert data into database in asp.net core mvc using ado.net. I am trying to insert images using that form. I created model for that. How can i insert more than one image for a single property? For example a book has many pictures, so how i can manage the code?

In your backend,configure the Model as below:
public class SomeViewModel
{
.......//other properties
public IFormFileCollection Pics { get; set; }
}
In your view,you could add the multiple attribute for multiple pictures:
#model SomeViewModel
<form asp-controller="Home" asp-action="Upload" enctype="multipart/form-data" method="post">
<input asp-for="#Model.id" />
<br />
<input asp-for="#Model.Pics" type="file" multiple />
<br />
<input type="submit" value="Upload"/>
</form>
The result:
For more details of file upload,you could check this document

Related

Thymeleaf set default value [duplicate]

I am programming in Spring and using Thymeleaf as my view, and am trying to create a form where users can update their profile. I have a profile page which lists the user's information (first name, last name, address, etc), and there is a link which says "edit profile". When that link is clicked it takes them to a form where they can edit their profile. The form consists of text fields that they can input, just like your standard registration form.
Everything works fine, but my question is, when that link is clicked, how do I add the user's information to the input fields so that it is already present, and that they only modify what they want to change instead of having to re-enter all the fields.
This should behave just like a standard "edit profile" page.
Here is a segment of my edit_profile.html page:
First Name:
Here is the view controller method that returns edit_profile.html page:
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEditProfilePage(Model model) {
model.addAttribute("currentUser", currentUser);
System.out.println("current user firstname: " + currentUser.getFirstname());
model.addAttribute("user", new User());
return "edit_profile";
}
currentUser.getFirstname() prints out the expected value, but I'm getting blank input values in the form.
Thanks.
Solved the problem by removing th:field altogether and instead using th:value to store the default value, and html name and id for the model's field. So name and id is acting like th:field.
I'm slightly confused, you're adding currentUser and a new'd user object to the model map.
But, if currentUser is the target object, you'd just do:
<input type="text" name="firstname" value="James" th:value="${currentUser.firstname}" />
From the documentation:
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html
I did not have a form with input elements but only a button that should call a specific Spring Controller method and submit an ID of an animal in a list (so I had a list of anmials already showing on my page). I struggled some time to figure out how to submit this id in the form. Here is my solution:
So I started having a form with just one input field (that I would change to a hidden field in the end). In this case of course the id would be empty after submitting the form.
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
The following did not throw an error but neither did it submit the animalIAlreadyShownOnPage's ID.
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
In another post user's recommended the "th:attr" attribute, but it didn't work either.
This finally worked - I simply added the name element ("id" is a String attribute in the Animal POJO).
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" name="id" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>

Multiple similar forms in same page

In Spring Boot with Thymeleaf, I have a page that should handle two forms corresponding to a same model Person. Each form can be submitted separately, so I use two methods in the controller:
#PostMapping(value="/", params={"submitFather"})
public String submitFather(
#ModelAttribute("fatherForm") Person fatherForm,
#ModelAttribute("motherForm") Person motherForm,
Model model) {
// ... Process fatherForm
// Return the updated page
model.addAttribute("fatherForm", fatherForm);
model.addAttribute("motherForm", motherForm);
return "index.html";
}
#PostMapping(value="/", params={"submitMother"})
public String submitMother(
#ModelAttribute("fatherForm") Person fatherForm,
#ModelAttribute("motherForm") Person motherForm,
Model model) {
// ... Process motherForm
// Return the updated page
model.addAttribute("fatherForm", fatherForm);
model.addAttribute("motherForm", motherForm);
return "index.html";
}
In my template:
<form id="fatherForm" th:object="${fatherForm}" method="post">
<label for="firstName">First name</label>
<input type="text" th:field="*{firstName}"><br>
<!-- ... other Person fields -->
<input type="submit" name="submitFather" value="Order">
</form>
<form id="motherForm" th:object="${motherForm}" method="post">
<label for="firstName">First name</label>
<input type="text" th:field="*{firstName}"><br>
<!-- ... other Person fields -->
<input type="submit" name="submitMother" value="Order">
</form>
The issue I have is that this leads to HTML IDs clashes. There will be for example two <input> with id firstName. This causes invalid HTML and interference between the fields from the two forms when submitted.
One solution would be to have two models, Father and Mother with fields named such as fatherFirstName to ensure no duplicate HTML IDs. But this leads to substantial code duplication, and long and different field names (while only the HTML IDs need to be different).
How can this be solved? Is there a way to tell Spring to prefix ids with some string while ensuring I can still use the same Person model for the two forms?

Create urls using forms in Thymeleaf

I am new to Thymeleaf, and I have an issue with dynamically creating URLs using forms.
I have a simple spring boot app that stores objects in a database, and I can query the database using simple urls. For instance, the url /distance/0.3 would return objects whose distance attribute is lower than or equal to 0.3. These urls work perfectly when I edit them in the browser.
I would like users to be able to set these search values themselves. I tried to create a simple form to create the above url with user inputs, but I am getting the following error:
Neither BindingResult nor plain target object for bean name 'dist' available as request attribute
I have tried with this in the html document:
<form th:action="#{/distance/{pathParam}(pathParam=${dist}}">`
<p>Distance: <input type="text" th:field="*{dist}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
and trying various answers from this discussion, but with no luck.
I have also tried to use the controller as suggested here, with this in the controller:
#GetMapping("/distance/search/")
public String userSetDistance(#RequestParam("dist") String dist) {
return "redirect:/distance/" + dist;
}
and this in the html file:
<form th:action="#{/distance/search/}">
<p>Distance: <input type="text" th:field="*{dist}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
But this did not work either.
Could you please help me with this? The idea is simple but I cannot get something that works... thank you!
UPDATE
Based on the below answer from MohamedSanaulla, I decided to use the controller to do this, created a "forms" object with the required fields and edited my code as follows:
<form action="#" th:action="#{/distance/search}" th:object="${param}" method="post">`
<p>Distance: <input type="text" th:field="*{dist}"/></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
#PostMapping("/distance/search")
public String userGetClose(#ModelAttribute ("param") Forms form) {
String distance = String.valueOf(form.getDist());
return "redirect:/distance/" + distance;
}
Ideally I wanted to create and call the url directly from the html page, to avoid going back to the controller just to create the url, but this works fine.
You have to either use ModelMap or Model in your controller and then use addAttribute to set the dist:
public String controllerMethod(#RequestParam("dist") String dist,
Model model){
model.addAttribute("dist", dist);
return "viewName";
}
Or Thymeleaf provides context object to get query params like ${param.dist} directly in your HTML
Update:
Just saw that there is a redirect: in the controller. So the dist is no longer available in the request param and hence ${param.dist} will not work. The easier solution is to use ModelMap and put the dist as part of the view model.

handle one to many relationship in thymeleaf using spring mvc

I'm having One entity as Vendor and Another as Address and the relationship between both of them is One To Many form Vendor to Address.
Note : I am using JPA
My Vendor Entity
public class Vendor {
private Integer id;
private String name;
private List<Address> address;
// getter and setters
}
Address class:
public class Address {
private Integer id;
private String addressline1;
private String addressline2;
//getter and setters
}
Now I am using Thymeleaf , I have a scenario where I need to add the address dynamically to a form for the particular vendor.
How do I do Object binding for the Address object in Vendor using Thymeleaf in spring mvc?
Comment if i didn't understand your question correct, it's a bit unclear to me...
In order to access the address(s) of a vendor, you provide a vendor within your controller (something like model.addAttribute("vendor", currentVendor);) and call vendor.address in your html file. Please note that this will give you a list so you need to iterate to show all address:
<tr th:each="address : ${vendor.address}">
<td th:text="${address.id}">1</td>
<td th:text="${address.addressline1}"></td>
<td th:text="${address.addressline2}"></td>
</tr>
Uhhh, that's tricky because binding to form doesn't work in a dynamic way. That means you can't do something like #Viergelenker suggests AND bind each address-object to his own form.
You can add a single address object to the model, e.g.
model.addAttribute("address", addressObject); // Snippet for Model-object
modelAndView.addObject("address", addressObject); // Snippet for ModelAndView object
and then define a form in yout template like:
<form .... method=".." th:object="${address}">
<input type="hidden" th:field="*{id}" >
<input type="text" th:field="*{addressline1}" >
<input type="text" th:field="*{addressline2}" >
</form>
Unfortunately it is not possible to add a array or list to the model and bind each object in that collection to his own form:
/* The following code doesn't work */
<th:block th:each="address : ${addresses}">
<form .... method=".." th:object="${address}">
<input type="text" th:field="*{addressline1}" >
...
</form>
</th:block>
or
/* The following code doesn't work */
<th:block th:each="address, stat : ${addresses}">
<form .... method=".." th:object="${addresses[__stat.index__]}">
<input type="text" th:field="*{addressline1}" >
...
</form>
</th:block>
What you can do is not to use form binding and just send some name-value pairs from forms without the binding (just use the name and the th:value attributes and not the th:field attribute in your forms) to the controller, get them there from the HttpServletRequest object and create/update/delete address-objects ... or bind the whole Vendor object to a form (note the use of stat.index):
<form th:object="${vendor}">
<input type="hidden" th:field="*{id}">
<input type="hidden" th:field="*{name}"> // feel free to make that field editable
<th:block th:each="addr, stat : *{address}">
<input type="hidden" th:field="*{address[__${stat.index}__].id}">
<input type="text" th:field="*{address[__${stat.index}__].addressline1}">
<input type="text" th:field="*{address[__${stat.index}__].addressline2}">
</th:block>
</form>

How to represent 2 model objects inside the thymeleaf template

i am working in this spring-boot project and i am returning a ModelAndView object from my controller method , i have added 2 objects to the ModelAndView. this part is working and i want to know how to represent the values inside the thymeleaf template.
public ModelAndView showEdit(#PathVariable int id,Customer cust,Model model){
ModelAndView view = new ModelAndView();
view.setViewName("editCustom");
view.addObject("cust",cust);
view.addObject("log",login);
}
inside the thymeleaf template.
<form action="#" th:action="#{/save}" th:object="${cust}" method="post">
Name:<input type="text" th:field="*{name}" />
i can fetch values in cust but i dont know how to get values from login.
i tried this but its not working.note that all input tags are inside the same form.
<input type="text" id="user" name="user" value="${login.uname}"/>
In your model you are adding login details as log and in your view your are using login
view.addObject("log",login);
versus
${login.uname}
Also thymeleaf uses an attribute processor which process attributes prefixed with th. Instead of using value use th:value as follows
<input type="text" id="user" name="user" th:value="${log.uname}"/>

Resources