I'm trying to define the action attribute of a form from the controller.
This is in my controller class:
model.addAttribute("action", "/signUnique(uClass=" + uClass + ")");
uClass is a string containing the value I want to pass in the url.
And this is in my html (thymeleaf) file:
<form th:action="#{${action}}" method="POST">
I'm getting this in the action:
/signUnique(uClass=2)
I'm new in thymeleaf and spring boot, and it is also my first time posting in stackoverflow, so please forgive me if I did something wrong.
Thx.
I would recommend you just build the entire url in your controller:
model.addAttribute("action", "/signUnique?uClass=" + uClass);
If you really do want to parse a Thymeleaf expression in your template, you'll need to use preprocessing. Something like this will work:
<form th:action="#{__${action}__}" method="POST">
Related
I have a problem with my edit page. When I submit I get this error:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods:
POST
.
I have no clue where it comes from as I am pretty new to Laravel.
web.php
Route::post('/admin/add_reseller','ResellerController#addReseller');
Controller.php
public function addReseller(){
return view ('admin.resellers.add_reseller');
}
add_reseller.blade.php
<form class="form-horizontal" method="post" action="" name="addreseller" id="addreseller">
{{ csrf_field() }}
Tip:
First of all, I would use named routes, that means you add ->name('someName') to your routes. This makes the use of routes way easier and if you decide that your url doens't fit you don't need to change it everywhere you used the route.
https://laravel.com/docs/7.x/routing#named-routes
e.g. Route::post('/admin/add_reseller',
'ResellerController#addReseller')->name('admin.reseller');
Problem:
What I see is, that you lack the value for the action attribute in your <form>. The action is needed, so that the right route is chosen, if the form gets submitted.
Solution:
I guess you just have to add action="{{route('admin.reseller')}}" for the attribute, so that the request goes the right route.
<form class="form-horizontal" method="post" action="" name="addreseller" id="addreseller">
Your action in the form is empty, you need to add the corresponding route there.
I'd suggest you to use named routes.
https://laravel.com/docs/7.x/routing#named-routes
In web.php
Route::post('/admin/add_reseller','ResellerController#addReseller')->name('admin.add.reseller');
and then in your blade file you could refer to the route using the route() function by passing the name of the route as an argument
<form class="form-horizontal" method="post" action="{{route('admin.add.reseller')}}" name="addreseller" id="addreseller">
I am in the process of learning Spring Boot and became unstuck when trying to post model data to an HTML file.
I have a controller, where I populate the model and call an HTML page from. When I put a breakpoint inside this method, the model data gets populated correctly, but the HTML page is rendered with only the name of the HTML file, and nothing else (no browser errors either). I am thinking it may have something to the with the file structure, and the fact that my RestController already has a path specified (because when I create a clean new controller with no explicit class-based #RequestMapping specified and call the template from the root path + name of HTML file, it renders correctly). I do have the ThymeLeaf dependency installed, and "userView.html" is placed inside the "template" directory.
ReaderController.java extract:
#RequestMapping("/reader")
public class ReaderController {
...
#RequestMapping(value = "/userView")
public String getUser(Model model) {
// business logic goes here
model.addAttribute("userName","Somebody");
model.addAttribute("url", "www.example.com");
return "userView";
}
userView.html extract:
<body>
<h1>User Data</h1>
<p th:text="'Username: ' + ${userName}"/>
<p th:text="'Url: ' + ${url}"/>
</body>
http://localhost:8080/reader/userView only renders the word "userView".
I found the solution to the issue. I inadvertently used the #RestController annotation instead of the #Controller annotation to the controller class. This link helps to explain the issue.
I would like to use a select box to redirect to an URL containing the select value.
Here bellow the HTML page with thymeleaf variables :
<form th:action="#{/app/}">
<select id="app" name="app">
<option th:each="app : ${apps}"
th:value="${app.id}"
th:text ="${app.name}">
</option>
</select>
<button>Go</button>
</form>
The controller is written as following :
#RequestMapping("/app/{appId}")
public ModelAndView getApp(#PathVariable String appId){...}
My goal is to access the controller with the URL : mydomain/app/{app.id}/
I tried to use th:field onto the select without success. I'm missing something here.
Please, could you explain me how to add the select value to the URL expected by the controller ?
Thank you for the hints
EDIT following #NicolaiEhemann answer
I moved to javascript using jquery and ajax :
$('button').click(function() {
$.ajax({
url: '/app/' + $('#app').val(),
dataType: 'html'
}).done(function(data) {
$('#result').html(data)
});
});
Thank you.
Thymeleaf will only generate static html code. To achieve what you want, you have to write client side javascript to handle the 'input' event event to change the form action when a different value is selected, or handle the form 'submit' event to override the default action of the form submission. The relevant js code will probably be dependent on which framework you use.
Simply, add the path variable to the form action with double uderscores around
i.e. replace <form th:action="#{/app/}"> with <form th:action="#{/app/__${app.id}__">
source: http://forum.thymeleaf.org/Sending-pathvariable-to-controller-td4028739.html
In the application I am working on, I have an Html page inside views folder and I have mentioned the action as follows.
<form name="form" onsubmit="return validateForm();" method="post" action="//Controllers/RegistrationController.cs">
The registration controller returns a view.
public ActionResult Detail(string name)
{
return View();
}
When I run the program, I get server not found error.
I also tried changing the action string to action="//Controllers/RegistrationController.cs/Detail"
but got the same error.
Does the action string have to be written in some other way?
Thank you very much in advance for your help.
Assuming you are using the default routes ({controller}/{action}/{id}) you need:
action="/Registration/Detail"
Actually I would recommend you using HTML helpers to generate forms and never hardcode them as you did:
#using (Html.BeginForm("Details", "Registration", FormMethod.Post, new { name = "form", onsubmit = "return validateForm();" }))
{
...
}
Description
You don't have to set the path like in your solution. You don't need to set Controllers because the framework knows that you mean the controller.
Assuming that you dont change the routing in global.asax, your RegistrationController.cs has an ActionMethod called Detail (decorated with [HttpPost]) and the following folder structure within your project.
Controllers/RegistrationController.cs
Views/Registration/Detail.cshtml
#using (Html.BeginForm("Detail", "Registration", FormMethod.Post, new { #onSubmit = "return validateForm();" }))
{
// Your Form's content
}
/registration/detail - you don't need to reference the path to the actual file. The framework finds the controller class and invokes the requested action for you. It uses the routes as defined in global.asax.cs to determine the controller and action from the url. The default route is {controller}/{action}/{id} where the first two have defaults of "Home" and "Index", respectively, and the third is optional. You can change this if you want by adding/modifying the route set up.
I am working on a form using the new Razor view engine, and am having an issue with a form field having an encoded value. I have the following code on my form:
<form id="handout" method="post" class="padded_form" enctype="multipart/form-data"
action="#Url.Remarketing().HandoutNew(Model.Inspection.InspectionId, Request.QueryString[QueryStringParamConstants.RedirectURL])">
<h2>Handout Options</h2>
<li>
#Html.Label("handout.Price", "Price")
#Html.TextBox("handout.Price", Model.Handout.Price)
</li>
where price is a decimal value. If I enter say "1,000" on the form, the value posted is: "&handout.Price=1%2c000" and the Price property on my entity does not get populated.
Is there a way to not encode this value when the form is posted?
Thanks.
You would have to use client-side javascript to normalize the value an remove any formatting characters.
Alternatively you could implement your own IValueProvider that could perform the conversion on the server before the model is databound.