Spring 3 checkbox list objects have null properties - spring-mvc

I may be hopelessly lost here, but having come from a MVC.NET world I cannot for the life of me figure this one out. I'm not getting any error messages, but all object properties submitted on a form submission are null. The objects themselves are not null, just their properties.
All I want to do is have a series of objects, represented by checkboxes on the form, after the forms submits. It's a little tricky as you can can see because of a nested list arrangement. The view renders perfectly on the GET request, but seems to forget everything when posted to the server. Does anyone have any examples of such a set-up? Could anyone suggest why all my objects loose their bindings?
My Controller:
#RequestMapping(value="/Search", method = RequestMethod.GET)
public String search(Model model)
{
Period periods = new Period();
SearchModel search = new SearchModel();
search.periods = periods.BuildPeriodList();
model.addAttribute("periods", periods.BuildPeriodList());
model.addAttribute(search);
return "search";
}
#RequestMapping(value = "/Search", method = RequestMethod.POST)
public String search(#ModelAttribute("searchModel") SearchModel search, BindingResult result)
{
System.out.println(Arrays.deepToString(search.periods));
return "search";
}
My View:
<div id="searchPage">
<div id="searchForm">
<form:form action="Search" method="post" modelAttribute="searchModel">
<h2>Search</h2>
<h2>Periods</h2>
<c:forEach items="${periods}" var="period" varStatus="index">
<form:checkbox path="periods[${index.count - 1}]" id="${period.name}" name="${period.name}" value="${period.name}"/>
<label for="${period.name}">${period.displayName}</label>
<div class="subPeriods">
<c:forEach items="${period.subPeriods}" var="subPeriod" varStatus="subIndex">
<form:checkbox path="periods[${subIndex.count - 1}].subPeriods" id="${subPeriod.name}" name="${subPeriod.name}" value="${period.name}"/>
<label for="${subPeriod.name}">${subPeriod.displayName}</label>
</c:forEach>
</div>
</c:forEach>
<div class="clear"></div>
<h2>Extras</h2>
<form:checkbox path="hasImage" name="hasImage" id="hasImage"></form:checkbox>
<label for="hasImage">Image</label>
<form:checkbox path="hasPaper" name="hasPapaer" id="hasPapaer"></form:checkbox>
<label for="hasPaper">Paper Data</label>
<form:checkbox path="hasExtended" name="hasExtended" id="hasExtended"></form:checkbox>
<label for="hasExtended">Extended Info</label>
<input type="submit" name="search" value="Search"></input>
</form:form>
</div>
<div id="searchResults">
</div>
<div class="clear"></div>

It's due to some of your checkboxes being bound to your "periods" model, while others being bound to your SearchModel model. The path attribute of the form:checkbox element tells how to bind the information.
Either include this within your SearchModel, or have another #ModelAttribute("periods") in your POST method.
I'd recommend sticking to one model, plus I'm not sure if you can have more than one #ModelAttribute in a controller method, something to try, though.

Related

TempData Dictionary is null after Redirect to page

So I have this issue that I am not unable to solve the way I think it's supposed to be solved.
I have an ASP.NET Core 2.1 Razor pages project. The code is pasted below and my problem is the following:
On the index page, I have a search form. The city name I enter in the search form gets used in the SearchResults OnPost method.
The OnPost redirects to OnGet which retrieves some results from the database based on the city passed in from the search form. From my understanding, TempData should be able to retain the value for the city passed in from the form, however, whenever I try to read TempData["CityFromForm"] in the OnGet method, the TempData dictionary is empty, even though that in the OnPost method I used the TempData.Keep method.
My current solution for this is using in memory cache to store the city value and pass it to the method that fetches the data from the database, but I would like to know why the TempData approach is not working.
On the index page on that project, there is a search from in which I enter a city for which I want to search the data, like so:
#model SearchDataViewModel
<form asp-page="/Search/SearchResults" method="post" class="col s6">
<div class="row">
<div class="input-field col s12">
<input placeholder="Please enter a city" type="text" name="City" class="validate autocomplete" id="autocomplete-input" autocomplete="off" />
<label for="City">City</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input id="StartDate" name="StartDate" type="text" class="datepicker datepicker-calendar-container">
<label for="StartDate">Start date</label>
</div>
<div class="input-field col s6">
<input id="EndDate" name="EndDate" class="datepicker datepicker-calendar-container" />
<label for="EndDate">End date</label>
</div>
</div>
<input type="submit" hidden />
</form>
What matters in that form is the city. That form gets sent to the SearchResults razor page.
SearchResults.cshtml.cs
public IActionResult OnPost()
{
// Cache search form values to persist between post-redirect-get.
var cacheEntry = Request.Form["City"];
_cache.Set<string>("City", cacheEntry);
TempData["CityFromFrom"] = Request.Form["City"].ToString();
TempData.Keep("CityFromForm");
return RedirectToPage();
}
// TODO: Find a better way to persist data between onPost and OnGet
public async Task OnGet(string city)
{
City = _cache.Get<string>("City");
var temp = TempData["CityFromForm"];
// Here I'd like to pass the TempData["CityFromForm"] but it's null.
await GetSearchResults(City); // this method just gets data from the database
}
TempData keys are prefixed by "TempDataProperty-". So if you have a key named "City", you access it via TempData["TempDataProperty-City"].
See https://www.learnrazorpages.com/razor-pages/tempdata
You also have a typo in the line where you assign the tempdata value: TempData["CityFromFrom"] should be TempData["CityFromForm"], I suspect.
So here is what I came up with, basically I get a city string from the search form. In the OnPost method I redirect to page where I add a route value which OnGet method can use.
In SearchResults.cshtml I added a #page "{city?}"
The url ends up looking like: https://localhost:44302/Search/SearchResults?searchCity={city}
In SearchResults.cshtml.cs
public async Task OnGet()
{
City = HttpContext.Request.Query["searchCity"];
PetGuardians = await GetSearchResults(City);
}
public IActionResult OnPost(string city)
{
return RedirectToPage(new { searchCity = city });
}

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.

Access value outside form using thymeleaf

I need to obtain vaulue of an input using thymeleaf and spring but haven't been able to do so. Since I need that value in a lot of the methods in the controller I can't put that input inside of one of the forms.
I tried to use javascript to pass on the value to a hidden input in the forms, however since I'm using th:each I'm only getting the value of the first input.
I also tried adding a string to the model and then trying to access that string with #ModelAttribute, but it didn't workout either.
This is the html:
<tr th:each="pro:${productos}">
<td th:text="${pro.id}">id</td>
<!-- More code here omitted for brevity-->
<td>
<div>
<form th:action="#{|/actualizarMas/${pro.id}|}" method="post">
<button type="submit" id="mas">+</button>
</form>
<form th:action="#{|/actualizarMenos/${pro.id}|}" method="post">
<button type="submit" id="menos">-</button>
</form>
<input name="masomenos"/>
<form th:action="#{|/${pro.id}|}" method="post">
<button type="submit">Borrar</button>
</form>
</div>
</td>
</tr>
This is the controller:
#RequestMapping(value = "/actualizarMenos/{productosId}", method = RequestMethod.POST)
public String eliminarUno(#PathVariable int productosId, RedirectAttributes redirectAttributes, #RequestParam("masomenos") String masomenos) {
//Code here using that string omitted for brevity
return "redirect:/";
}
I need to access the input with the name "masomenos", if that is posible, how could I do it?, if not, what options do I have? besides creating inputs inside all the forms.
Thank you very much.

ASP.NET MVC pass data from partial view

How can I pass data from partial view on submit form in ASP.NET MVC.
#using (Html.BeginForm("Edit", "BlogPost", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
................
#Html.Partial("PostImagesForPost",Model.PostImages)
}
PostImagesForPost - partial view:
#model IEnumerable<Blog.Models.PostImage>
<script type="text/javascript" src="~/Scripts/jquery.zoom.min.js"></script>
<div>
#{
List<Blog.Models.PostImage> images = Model.ToList();
<ul class="images">
#foreach (var img in images)
{
string parameterValue_small = "~/BlogPhotos/120/" + img.Photo.ToString();
string parameterValue_big = "~/BlogPhotos/600/" + img.Photo.ToString();
<li>
<div id="jquery-image-zoom-example">
<span data-postid="#img.ID" data-delete="true" class="deletespan"></span>
<a href="#Url.Content(parameterValue_big)">
<img src="#Url.Content(parameterValue_small)" data-postid="#img.ID" class="zm" onclick="$('.jquery-image-zoom img').click()" />
</a>
<input type="checkbox" checked="checked" name="selectedImagesForDelete" style="display:none;" data-postid="#img.ID" value="#img.ID" />
</div>
</li>
}
</ul>
}
On submit function the parameter selectedImagesForDelete is null.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Post post,string[] selectedImagesForDelete)
{...........}
This has nothing to do with the fact you're using a partial, and everything to do with how the modelbinder in MVC works. For iterable posted items, the model binder expects field names in the form of ListProperty[index].ModelProperty. The problem is that the Html.* family of helpers will not create this name properly unless they are passed an indexed value, which you can't achieve with foreach. The solution is to simply use for, instead:
#for (var i = 0; i < images.Count(); i++)
{
Html.EditorFor(m => image[i].SomeProperty)
}
By passing in a value that's indexed (images[i]), the helper recognizes that it needs to add the proper indexed html prefix to the name, so that the modelbinder will understand where to stuff the value when it's posted back.
Though, in your case, you seem to actually just be manually specifying the HTML for the fields, which is fine, but you're responsible at that point for getting the name values right.
I believe your name property needs to have indexes in the name:
Create a index variable called index and increment it after each iteration
<input type="checkbox" name="selectedImagesForDelete[index]" value="2">
Actually it was a problem with the javascript file. The checkboxes were never checked.
<input type="checkbox" name="selectedImagesForDelete" value="#img.ID" />
But I resolved that problem and now everything works like expected.
But thanks for trying to help me. I appreciate it.

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.

Resources