Form submit with a file in Spring mvc + bootstrap - spring

Its a two part question.
I am trying to submit a pop up form with a file and textarea. I am not able to receive file in my controller code.
Part 1 - How do I receive the file at the controller.
Part 2 - Once I submit the form, how do I close the popup and remain on the same page so that URL does not change.
Popup code-
<form name="eperform">
<div class="modal fade" id="export" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<span class="glyphicon glyphicon-remove" aria-hidden="true" style="padding-top: 10px;"></span>
</button>
<h4 class="modal-title custom_align" id="Heading">Provide ID's here:</h4>
</div>
<div class="form-group">
<div>
<fieldset style="margin-left: 10px;">
<legend style="font-size: medium;">File Upload</legend>
<input id="fileUpload" name="fileUpload" type="file" style="margin-left: 20px"/>
</fieldset>
</div>
<br/>
<div>
<fieldset style="margin-left: 10px;">
<legend style="font-size: medium;">Ids</legend>
<label for="envIds"></label>
<textarea class="form-control noresize" rows="4" style="width:98% " name="ids" id="ids" value="">
</textarea>
<input type="hidden" id="server" name="server" value="${server}">
<input type="hidden" id="port" name="port" value="${port}">
<input type="hidden" id="queuename1" name='queuename1' value="">
<input type="hidden" id="environment" name="environment" value="${environment}">
</fieldset>
</div>
</div>
<div class="modal-footer ">
<button type="button" class="btn btn-success" id="eid"
onclick="exportObjects(document.getElementById('ids').value,document.getElementById('queuename1').value,'${port}','${server}','${environment}',document.getElementById('fileUpload').value)">
<span class="glyphicon glyphicon-ok-sign"></span>Export
</button>
<button type="button" class="btn btn-default" data-dismiss="modal">
<span class="glyphicon glyphicon-remove"></span> Cancel
</button>
</div>
</div>
</div>
</div>
</form>
Javascript code-
function exportObjects(ids, queueName, port, server, environment, fileUpload) {
var strHREF = "/exportObjects?ids=" + ids
+ "&queueName=" + queueName + "&port=" + port + "&server="
+ server + "&environment=" + environment +"&fileUpload=" + fileUpload;
document.eperform.action = strHREF;
document.eperform.submit();
}
Controller code-
#RequestMapping(value="/exportObjects", method = RequestMethod.GET)
public ModelAndView exportObjects(HttpServletRequest request) throws Exception{
String server =request.getParameter("server");
String port =request.getParameter("port");
String environment = request.getParameter("environment");
String type =request.getParameter("queueName");
String ids = request.getParameter("ids");
CommonsMultipartFile file = (CommonsMultipartFile) request.getAttribute("fileUpload");
if(file != null && file.getSize() != 0){
String path=request.getServletContext().getRealPath("/");
String filename=file.getOriginalFilename();
System.out.println(path+" "+filename);
try{
InputStream in = file.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString());
}catch(Exception e){System.out.println(e);}
}
// Perform action on ids and file data
ModelAndView model = new ModelAndView();
// I do not know what to do here.
return model;
}

It seems that you are not familiar with web developement,I recommend you take some time to review the java web development knowledge.
Below are the answer for your two questions:
If you want to upload a file to the server,you must add enctype="multipart/form-data" to your form
<form name="eperform" enctype="multipart/form-data">
<div>
<fieldset style="margin-left: 10px;">
<legend style="font-size: medium;">File Upload</legend>
<input id="fileUpload" name="fileUpload" type="file" style="margin-left: 20px"/>
</fieldset>
</div>
</form>
If you want to stay on the same page,you should using an asynchronous method to submit your action,and Ajax is your best choice.You need to submit your request and in the success callback method close the popup dialog.
$.ajax({
url:"exportObjects",
type:"post",
data:{
queueName:queueName,
port:port,
server:server,
environment:environment
},
success:function(data){
//if the request submit success,invoke 'close' method to close the dialog
$("#dialog_div").dialog("close");
}
});
In your springmvc code,you should not use ModelAndView because it will forward to a new page,you need to return an original string,like the code listed below,after that you can use MultipartFile to get your upload file:
#RequestMapping(value="eperform",method=RequestMethod.POST)
#ResponseBody
public String updateNodeRelation(#RequestParam(value="fileUpload")
MultipartFile file,HttpServletRequest request) {
System.out.println(file.getOriginalFilename());
return "success";
}
UPDATED
If you want to submit a file and then stay on the same page,then you need to use iframe and not use Ajax,as below:
<!-- using iframe to stay on the same page-->
<form id="eperform"name="eperform" action="exportObjects" enctype="multipart/form-data"
target="hidden_frame">
<div>
<fieldset style="margin-left: 10px;">
<legend style="font-size: medium;">File Upload</legend>
<input id="fileUpload" name="fileUpload" type="file"
style="margin-left: 20px"/>
</fieldset>
</div>
<iframe id="hidden_frame" name="hidden_frame"
style="display:none"/>
<button type="button" onclick="submitFile()">Submit</button>
</form>
And using the below Javascript code to submit the form and close popup dialog**
function submitFile(){
$("#eperform").submit();
$("#dialog_div").dialog("close");
}

Related

pass object from HTML template back to the controller

I have the following HTML block. I want to pass the object "jobDTO" back to the contoller "/deleteJob" method. Whatever I do I am getting null object.
<th:block th:if="${jobDTO != null}" th:each="jobDTO: ${allJobDTOs.get(jobGroup)}">
<div id="accordion2" style="margin-bottom: 3px;">
<div class="card" id="headingOne">
<div class="card-header" style="padding: 0">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" th:attr="data-target='#accordion2_'+${jobDTO.identity.name}"
aria-expanded="true" aria-controls="collapseChild" >
<p class="font-weight-bold custom-p identity-black" > Job Identity </p>
<p class="custom-p" style="padding-left: 52px;" th:text="${jobDTO.identity.group} +' , ' + ${jobDTO.identity.name}"></p>
</button>
</h5>
</div>
<div th:id="'accordion2_'+${jobDTO.identity.name}" class="collapse" aria-labelledby="headingOne" data-parent="#accordion2">
<div class="card-body">
<dl class="row">
<dt class="col-lg-3">Trigger List</dt>
<dd class="col-sm-9">
<th:block th:each="trigger: ${jobDTO.triggers}">
<p><b>nextFireTime</b> <span th:text="${trigger.nextFireTime}"> </span></p>
<hr>
</th:block>
</dd>
</dl>
<!-- important part.. how to pass the jobDTO object back to the controller -->
<form id="form2" action="#" th:action="#{/deleteJob}" th:object="${jobDTO}" th:method="post">
<input type="text" th:value="*{identity.name}" th:field="*{identity.name}" hidden/>
<button type="submit" value="Submit" class="btn btn-danger btn-sm" >Delete Job</button>
</form>
</div>
</div>
</div>
</div>
</th:block>
my controller relevant parts are:
#GetMapping(value = "/deleteJob")
public String deleteJobPage(Model model) {
model.addAttribute("jobDTO", new ScheduleJobDTO());
//Returns the Home page with the prepared model attributes
return "Home";
}
// =================
#PostMapping("/deleteJob")
public String deleteJob(#ModelAttribute final ScheduleJobDTO jobDTOReturn, BindingResult bindingResult, Model model) {
// I want to receive the jobDTO object here
schedulerService.deleteJobFromGroup(jobDTOReturn.getIdentity().getGroup(),
jobDTOReturn.getIdentity().getName());
return "redirect:/";
}
what I am missing here?
I think there is an error in your input tag, try this :
<input type="text" th:value="${jobDTO.identity.name}" th:field="*{identity.name}" hidden/>

Spring MVC Controller not receiving atribute from Template with Thymeleaf

I have a template which represents a list of notes that are retrieved from a database
<tr th:unless="${#lists.isEmpty(allNotes)}"
th:each="note : ${allNotes}">
<td>
<form action="#" method="POST" th:action="#{/home/editNote}"
th:object="${note}">
<input type="hidden" id="noteId" name="noteId" th:value="*{noteId}">
<button type="button" class="btn btn-success"
onclick="editNoteModal('updateNote', this.getAttribute('data-noteId'),
this.getAttribute('data-noteTitle'),
this.getAttribute('data-noteDescription'))">Edit
</button>
</form>
<form action="#" method="POST" th:action="#{/home/deleteNote}">
<input type="hidden" name="noteId" th:value="*{note.noteId}">
<a class="btn btn-danger">Delete</a>
</form>
</td>
<th scope="row" th:text="${note.noteTitle}">Example Note Title</th>
<td th:text="${note.noteDescription}">Example Note Description</td>
</form>
</tr>
</tbody>
In the GUI It looks like this
This is my modal code which should open after I click on the edit button:
<div class="modal fade" id="editNoteModal" tabindex="-1" role="dialog" aria-labelledby="noteModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editnoteModalLabel">Note</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="note-title" class="col-form-label">Title</label>
<input type="text" name="noteTitle" class="form-control" id="editNoteTitle"
maxlength="20" required>
</div>
<div class="form-group">
<label for="note-description" class="col-form-label">Description</label>
<textarea class="form-control" name="noteDescription" id="editNoteDescription"
rows="5" maxlength="1000" required></textarea>
</div>
<button id="editNoteSubmit" type="submit" class="d-none"></button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="$('#editNoteModal').click();">
Save
changes
</button>
</div>
</div>
</div>
</div>
</div>
In the GUI it looks like this:
I want to be able to edit given note and then send the edited id to the controller so I can update this change within the database. I have correct database logic for the update, I just don't know the way how to send the given notes id and changed information to my controller.
#PostMapping("/editNote")
public String editNote(#ModelAttribute(value = "note") Note note,
#ModelAttribute(value = "noteId") NoteIdModel noteIdModel, Model model,
Authentication authentication) {
System.out.println("noteid " + note.getNoteId());
System.out.println("noteidHidden " + noteIdModel.getNoteIdHidden());
System.out.println("notedesc" + note.getNoteDescription());
noteService.editNote(note, authentication);
return "result";
}
However, the incoming noteId is null. I have checked the database and the note with correct id is indeed in the database and is also retrieved from the database. It's just not sent to the controller.
Try this one:
HTML fragment
<tr th:unless="${#lists.isEmpty(allNotes)}"
th:each="note : ${allNotes}">
<td>
<button type="button" class="btn btn-success"
th:data-noteId="${note.noteId}"
th:data-noteTitle="${note.noteTitle}"
th:data-noteDescription="${note.noteDescription}"
onclick="editNoteModal('updateNote', this.getAttribute('data-noteId'),this.getAttribute('data-noteTitle'),this.getAttribute('data-noteDescription'))">Edit
</button><br/>
<a class="btn btn-danger">Delete</a>
</td>
<td scope="row" th:text="${note.noteTitle}"></td>
<td th:text="${note.noteDescription}"></td>
</tr>
JS fragment
/**
* Fill edit modal with current information
*/
function editNoteModal(modal, noteId, noteTitle, noteDescription) {
$('#editnoteModalLabel').text("Note " + noteId);
$('#editNoteId').val(noteId);
$('#editNoteTitle').val(noteTitle);
$('#editNoteDescription').val(noteDescription);
$('#editNoteModal').modal("show");
}
/**
* Save to backend edit information
*/
function save() {
var noteId = $('#editNoteId').val();
var noteTitle = $('#editNoteTitle').val();
var noteDescription = $('#editNoteDescription').val();
$.ajax({
url : "./editNote",
method : "POST",
headers : {
'Content-Type' : 'application/json'
},
data : JSON.stringify({
noteId : noteId,
noteTitle : noteTitle,
noteDescription : noteDescription
}),
success : function(result) {
$('#editNoteModal').modal("hide");
alert(result);
}
})
}
Backend
#PostMapping(path = "/editNote", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> editNote(#RequestBody Note note) {
System.out.println("noteid " + note.getNoteId());
System.out.println("noteidTitle " + note.getNoteTitle());
System.out.println("notedesc" + note.getNoteDescription());
//Save in database
return ResponseEntity.ok("OK");
}
This is how I did while I was trying to pass the id to open a modal by finding details using that id:
<a href="#" class="btn btn-sm btn-primary"
th:data-parameter1="${user.useruuid}"
onclick="openUserModal(this.getAttribute('data-parameter1'));">Details</a>
And then somewhere in your JavaScript, you can something (similar) like this:
<script type="text/javascript" th:fragment="includeModalScript">
function openUserModal(id) {
$.ajax({
url: "/findOnebyId?id="+ id,
success: function(data){
alert(id);
.......
</script>
And my controller looked like this:
#GetMapping("/findOnebyId")
#ResponseBody
public AppUser findOneByUUID(String id) {
....
}
You can take a look here, here and here for a working demo similar to your issue/requirement.

Core MVC 2 and Ajax wrong data type

I apologize for the subject topic too general, I have difficulties with Ajax work at all, I'm not able to sent/get up any response. The topic is probably duplicated, but I do not see the error in my code. All tutorials I found say the same thing but it still dont work for me, please take a look.
View
#model ValueTypeEditViewModel
#{
ViewBag.Title = "Dodaj Wartość";
Layout = "_AdminLayout";
}
<div class="col">
<form asp-action="EditValue" method="post">
<input type="hidden" asp-for="ValueType.ValueId" />
<input type="hidden" asp-for="ValueType.TypeId" />
<div class="form-group">
<label asp-for="ValueType.Value" class="m-1"></label>
<div><span asp-validation-for="ValueType.Value" class="text-danger"></span></div>
<input asp-for="ValueType.Value" class="form-control" />
</div>
#if (Model.IsSysParam)
{
<div class="form-group">
<label asp-for="ValueType.Controller" class="m-1"></label>
<div><span asp-validation-for="ValueType.Controller" class="text-danger"></span></div>
<input asp-for="ValueType.Controller" class="form-control" />
</div>
<div class="form-group">
<label asp-for="ValueType.Code" class="m-1"></label>
<div><span asp-validation-for="ValueType.Code" class="text-danger"></span></div>
<input asp-for="ValueType.Code" class="form-control" />
</div>
<div class="form-group">
<label asp-for="ValueType.Description" class="m-1"></label>
<div><span asp-validation-for="ValueType.Description" class="text-danger"></span></div>
<textarea asp-for="ValueType.Description" class="form-control"></textarea>
</div>
<div class="form-group">
<label asp-for="ValueType.IsSysParam" class="m-1"></label>
<div><span asp-validation-for="ValueType.IsSysParam" class="text-danger"></span></div>
<input type="checkbox" asp-for="ValueType.IsSysParam" class="form-control" />
</div>
}
#if (Model.ValueType.ValueId != 0)
{
<div class="form-group">
<label asp-for="ValueType.CreateDate" class="m-1"></label>
<label class="m-1">#Model.ValueType.CreateDate</label>
</div>
<div class="form-group">
<label asp-for="ValueType.EditDate" class="m-1"></label>
<label class="m-1">#Model.ValueType.EditDate</label>
</div>
}
#*#if (!Model.IsSysParam)
{
<div class="row">
<div class="col-5">
<select id="lbProducts" class="form-control" asp-items="Model.Products" size="#Model.ListBoxSize" multiple></select>
<label class="m-1">Lista Przedmiotów</label>
</div>
<div class="col-1 align-self-center">
<div class="d-flex justify-content-center">
<button id="addItems" class="btn btn-light mt-1" type="button"><i class="fa fa-long-arrow-right" aria-hidden="true"></i></button>
</div>
</div>
<div class="col-5">
<select id="lbAddedProducts" class="form-control" size="#Model.ListBoxSize" multiple></select>
#*<form method="post">
<button asp-page-handler="saveValueItems" id="saveValueItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-floppy-o" aria-hidden="true"></i></button>
</form>
<button id="removeItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
</div>
</div>
}*#
<div class="text-left">
<button class="btn btn-primary mt-1" type="submit">Zapisz</button>
</div>
</form>
<form asp-route="#(Model.IsSysParam ? RouteUrl.Name.SystemList : RouteUrl.Name.CategoryList)" method="post">
<div class="text-left">
<input type="hidden" name="isSysParamCategory" value="#Model.IsSysParam.ToString()" />
<button class="btn btn-secondary btn mt-1">Anuluj</button>
</div>
</form>
<form method="post">
#if (!Model.IsSysParam)
{
<div class="row">
<div class="col-5">
<select id="lbProducts" class="form-control" asp-items="Model.Products" size="#Model.ListBoxSize" multiple></select>
<label class="m-1">Lista Przedmiotów</label>
</div>
<div class="col-1 align-self-center">
<div class="d-flex justify-content-center">
<button id="addItems" class="btn btn-light mt-1" type="button"><i class="fa fa-long-arrow-right" aria-hidden="true"></i></button>
</div>
</div>
<div class="col-5">
<select id="lbAddedProducts" class="form-control" size="#Model.ListBoxSize" multiple></select>
<button asp-page-handler="saveValueItems" id="saveValueItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-floppy-o" aria-hidden="true"></i></button>
<button id="removeItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
</div>
</div>
}
</form>
</div>
At View you can see comented code started with - '#if (!Model.IsSysParam)'. Firstly I tried to fire Ajax from 'main' from with asp-page-handler="saveValueItems" at button. Then I added nested form in form with post (there is commented too), in the end I tried to created separeted form in the bottom of example. (by the way, I'm a beginner with mvc and don't really know if I can nesting form in form)
All the time I get the same error
Ajax
$(saveValueItems).click(function () {
var data = [];
var addedItems = $(addedItemList).find('option');
for (var i = 0; i < addedItems.length; i++) {
var item = addedItems[i];
data.push($(item).val());
}
$.ajax({
type: "POST",
url: "/admin/category/editvalue/96/35?handler=saveValueItems",
data: JSON.stringify(data),
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log('spoko');
},
failure: function (response) {
alert(response);
}
});
})
I hardcoded url to be sure I send request to good action. I have this in mind to test only with this one item/values.
Controller
[ValidateAntiForgeryToken]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "editvalue/{typeId?}/{valueId?}", Name = RouteUrl.Name.CategoryEditValueAjax)]
public ActionResult OnPostSaveValueItems([FromBody] int[] arrValueItems)
{
string test = "Hello Response Back";
return new JsonResult(test);
}
Startup.cs
I added to Startup.cs ValidateAntiForgeryToken before AddMvc() too
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
services.AddMvc();
Question:
I do not understand why I am sending the wrong data type. I want to send an int table and I receive a message that I'm sending ValueType and the view is expecting ValueTypeEditViewModel.
I do not know where to look for the cause of the error
1 Edit:
All actions for edit page
[HttpPost]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.System + RouteUrl.Slash + "[action]/{typeId?}", Name = RouteUrl.Name.SystemCreateValue)]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "[action]/{typeId?}", Name = RouteUrl.Name.CategoryCreateValue)]
public ViewResult CreateValue(int typeId, bool isSysParamCategory)
{
return View(RouteUrl.Edit + RouteUrl.Value, new ValueTypeEditViewModel(typeId, isSysParamCategory, repositoryProduct.Products, Convert.ToInt32(repository.GetSysParamByCode(SysParams.ProductListBoxSize))));
}
[HttpGet]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.System + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.SystemEditValue)]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.CategoryEditValue)]
public ViewResult EditValue(int typeId, int valueId)
{
bool isSysParamCategory = repository.GetCategoryByTypeId(typeId).IsSysParam;
return View(RouteUrl.Edit + RouteUrl.Value, new ValueTypeEditViewModel(repository.GetValue(typeId, valueId), isSysParamCategory, repositoryProduct.Products, Convert.ToInt32(repository.GetSysParamByCode(SysParams.ProductListBoxSize))));
}
[HttpPost]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.System + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.SystemEditValue)]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.CategoryEditValue)]
public IActionResult EditValue(AureliaCMS.Models.ValueType valueType)
{
if (ModelState.IsValid)
{
repository.SaveValueType(valueType);
return View(RouteUrl.Save, new SaveCategoryType(repository.GetCategoryByTypeId(valueType.TypeId).IsSysParam, valueType.Value, false));
}
else
{
return View(valueType);
}
}

FormCollection parameter is empty while using #Ajax.BeginForm and html5 controls

I'm developing ASP.NET MVC5 project with boostrap, jquery, jquery UI. Submit is working fine but FormCollection in create Action is arriving empty in HomeController. I don't know what I'm doing wrong or is missing. PLease need help. Below snippet code.
Index.cshtml:
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Empleado</h4>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("Create", "Home", new AjaxOptions() { HttpMethod = "post" }, new { id = "dialog", name = "dialog" }))
{
<div class="panel">
<div class="panel-body">
<div class="form-group">
<label class="control-label">Nombres</label>
<input type="text" class="form-control" id="modalNombres" placeholder="Nombres" />
</div>
<div class="form-group">
<label class="control-label">Apellidos</label>
<input type="text" class="form-control" id="modalApellidos" placeholder="Apellidos" />
</div>
<div class="form-group">
<label class="control-label">Fecha de Nacimiento</label>
<input type="text" class="form-control" id="modalFechaNacimiento" placeholder="Fecha Nacimiento" />
</div>
<div class="form-group">
<label class="control-label">Tipo Documento</label>
<select class="form-control" id="modalTipoDocumento">
<option class="placeholder" selected disabled value="">--- Seleccione ---</option>
#foreach (var item in ViewBag.TiposDocumento)
{
<option value="#item.Id">#item.Descripcion</option>
}
</select>
</div>
<div class="form-group">
<label class="control-label">Número de Documento</label>
<input type="text" class="form-control" id="modalNumeroDocumento" placeholder="Número Documento" />
</div>
</div>
<div class="panel-footer">
<button type="button" role="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" role="button" class="btn btn-primary" id="btnGrabar">Grabar</button>
</div>
</div>
}
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
HomeController is:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
string nombres = collection["modalNombres"];
return RedirectToAction("Index");
}
catch
{
return View();
}
}
None of you <input> elements have name attributes so there is nothing sent to the server. Change
<input type="text" class="form-control" id="modalNombres" placeholder="Nombres" />
to
<input type="text" class="form-control" name="modalNombres" placeholder="Nombres" />
There is no need for id attributes unless you using javascript/jquery to refer to them.
However, I very strongly recommend you go to the MVC site and work through some basic tutorials and learn how to generate a view in MVC. You should have a model, use the strongly typed html helpers to bind to the properties of your model, and the POST method should have a parameter for the model so it is bound (you should never use FormCollection in MVC)
Note also, you using Ajax.BeginForm() which uses ajax to post the form values so return RedirectToAction("Index"); in your POST method is pointless. Ajax calls stay on the same page, they do not redirect.

While form submitting using ajax..getting Post not supported error ...don't know what is the error?

I am using form submission using AJAX in Spring MVC and Thymeleaf. When I try to submit it it shows
Post method is not supported
I can't figure out the mistake in my code:
<form class="form-horizontal" action="#" th:action="#{/teacher/teacherProfileUpdation}" th:object="${teacherProfileDetailsList}"
id="saveTeacherForm" method="POST" >
<br />
<div class="row">
<div class="col-lg-14 col-md-12">
<br />
<h5 style="margin-left: 15%;">Personal Details</h5>
<hr />
<div class="form-group">
<label class="col-sm-3 control-label">Name</label>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher first name" id="txtTeacherFname" th:field="*{firstName}" type="text" class="form-control" />
</div>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher middle name" id="txtTeacherMname" th:field="*{middleName}" type="text" class="form-control" />
</div>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher last name" id="txtTeacherLname" th:field="*{lastName}" type="text" class="form-control" />
</div>
</div>
</div>
<div class="col-lg-14 col-md-12">
<div class="form-actions">
<input type="hidden" id="hdnStudentByIdInSchoolAdmin" value="0" />
<input type="button" class="btn btn-info pull-right" id="btnUpdateTeacherProfile" value="Save" />
</div>
</div>
</div>
JS:
saveTeacherProfile :function(){
$("#saveTeacherForm").ajaxForm({
success : function(status) {
alert("success");
},
}).submit();
}
Controller:
#RequestMapping(value = "/updateTeacherProfile", method = RequestMethod.POST)
public String updateTeacherProfile( TeacherProfileDetails teacherProfileDetails){
System.out.println("-----------"+teacherProfileDetails.getFirstName()+"-------------");
System.out.println("-----------"+teacherProfileDetails.getLastName()+"-------------");
System.out.println("-----------"+teacherProfileDetails.getMiddleName()+"-------------");
return "success";
}
You are posting the form, but most likely your Spring controller is not configured to accept POST requests. Try this in your server-side Controller class for this page:
#RequestMapping(..., method = { RequestMethod.GET, RequestMethod.POST }, ...)
public void myControllerMethod()
{
#RequestMapping(..., method = { RequestMethod.GET, RequestMethod.POST }, ...)
public String updateTeacherProfile( TeacherProfileDetails teacherProfileDetails){
//ur Logic
}

Resources