How to pass value from view to controller - ajax

In controller i have function public ActionResult Index(int id,int test= 0,int to=10){} I try to change value test from view on click to get test+=10 but i dont know how. I tryed with action link and ajax but its not working. Any ideas?
My view code :
<html ng-app>
<head>
<meta name="viewport" content="width=device-width" />
<title>Countries</title>
<link href="~/Content/style.css" rel="stylesheet" />
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
<table>
<tr>
<td><h3>Matches</h3></td>
</tr>
<tr>
</tr>
#foreach (var i in Model.ListMatch)
{
<tr>
<td>#Html.ActionLink(i.Description, "", new { id = i.Id })</td>
</tr>
}
</table>
</div>
</body>
</html>
I return results to ng-view. Can i do something like

This question isn't explained very well, but from what I gather you want to be able to make a change to a value without reloading the page or leaving that view.
In order to do this you have to use AJAX. I know you said you tried AJAX but perhaps you got something wrong. Try this:
$('#yourbutton').click(function() {
$.post( "/YourController/YourFunction", function() {
alert( "success" );
});
});

Related

Spring + Thymeleaf + Dropzone

I might sound strange with this question but I'm very new into those three technologies - Spring, Thymeleaf and Dropzone.
I am currently trying to get a html page resulting from a response from my Spring Controller + Thymeleaf with a request from a Dropzone file upload.
So my Controller receive the file from dropzone, reads it, apply some parsing and return the result as a html page, like a report.
It works as expected if I use a simple form like the one available in Spring tutorial site.
But when I put Dropzone I simply can't get the result from this html page.
I'll leave here my upload html (I've been trying to get the result and print into a div, without success):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>My upload form with Dropzone</title>
<link rel="stylesheet" href="https://unpkg.com/dropzone#5/dist/min/dropzone.min.css" type="text/css" />
<script src="https://unpkg.com/dropzone#5/dist/min/dropzone.min.js"></script>
<script>
Dropzone.options.myDropZone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: false,
parallelUploads: 1,
maxFiles: 1,
paramName: "file",
// The setting up of the dropzone
init: function() {
var myDropzone = this;
var submitButton = document.getElementById("btnStartUpload");
submitButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
this.on("sendingmultiple", function(file, xhr, form) {
form.append("file", file);
});
this.on("success", function(file, response) {
console.log(response);
$(".result").html(response);
});
}
}
</script>
</head>
<body>
<div id="dropzone">
<form id="myDropZone" class="dropzone" th:action="#{/upload}" method="POST" enctype="multipart/form-data">
<div class="previews"></div>
<button id="btnStartUpload">Submit file!</button>
</form>
</div>
<div id="result" class="result"></div>
</body>
My Controller:
#PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadFile (#RequestParam("file") MultipartFile file, ModelMap model)
{
try
{
// parse file and insert a collection into attribute, to be used in the 'result' page.
model.addAttribute("fields", /*collection*/);
return "result";
}
catch (IOException e)
{
e.printStackTrace();
return "failed";
}
}
And then my result html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>My result page</title>
</head>
<body>
<table>
<tr>
<td>F1</td>
<td>F2</td>
<td>F3</td>
</tr>
<th:block th:each="field : ${fields}">
<tr>
<td th:text="${field.name}"></td>
<td th:text="${field.value}"></td>
<td th:text="${field.description}"></td>
</tr>
</th:block>
</table>
</body>
</html>

Thymeleaf can't see For-each variable

Here is my Service ( It just gets a list of entities )
#Service
public class ProcedureService {
#Autowired
ProcedureRepository procedureRepository;
public List getProceduresList() {
List<Procedure> procedureList;
procedureList = procedureRepository.findAll();
return procedureList;
}
}
Here is my Controller. It just puts list he gets to view.
#Controller
public class ServicesController {
#Autowired
ProcedureService procedureService;
#GetMapping("/services")
public String getCustomer(Model model) {
List<Procedure> procedures = procedureService.getProceduresList();
model.addAttribute("procedures", procedures);
return "services";
}
}
And here is my real problem. Thyme leaf just doesn't see the entity in a List ( it sees the list though ). Here is my screen and full code of View
<!DOCTYPE html>
<html lang="en">
<head>
<title>SpringMVC + Thymeleaf + Bootstrap 4 Table Example</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Customer Table</h1>
<div class="row col-md-7 table-responsive">
<table id="customerTable" class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Street</th>
<th>Postcode</th>
</tr>
</thead>
<tbody>
<tr th:each="procedure: ${procedures}">
<td th:text="${procedure.}" />
<td th:text="${procedure.getId}" />
</tr>
</tr>
</tbody>
</table>
</div>
</div>
I forgot about html lang="en" xmlns:th="http://www.thymeleaf.org" in html so th wasn't really working.

vue.js: Error while using v-for

I want to render a table dynamically, based on ajax requests. The Backend is set up properly and when I execute the code the data from the response package is successfully loaded into my variables.
However, when viewing it in the browser, console logs the following error:
[Vue warn]: Failed to generate render function:
SyntaxError: Unexpected token - in
with(this){return _c('div',{attrs:{"id":"app"}},[_m(0),_v(" "),_c('table',[_c('tbody',[_c('tr',_l((header),function(head-item){return _c('th',{domProps:{"textContent":_s(head-item)}})})),_v(" "),_l((data),function(entry){return _c('tr',_l((entry),function(item){return _c('td',{domProps:{"textContent":_s(item)}})}))})],2)])])}
(found in <Root>)
My app.js file:
new Vue({
el: '#app',
data: {
header: [],
data: [],
},
mounted() {
axios.get('/contacts').then(response => this.load_response(response));
},
methods: {
load_response(response) {
this.header = response.data.header;
this.data = response.data.data;
}
}
});
And my html-file:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TestProject</title>
<body>
<div id="app">
<table>
<tr>
<th>TestHeader/th>
</tr>
<tr>
<td>TestItem</td>
</tr>
</table>
<table>
<tr>
<th v-for="head-item in header" v-text="head-item"></th>
</tr>
<tr v-for="entry in data">
<td v-for="item in entry" v-text="item"></td>
</tr>
</table>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="/js/app.js"></script>
</body>
</html>
When I try it in the browser, the first (dummy) table is shown for half a second or so, before it gets hidden. Then the page is blank.
EDIT: The json received from the server is in the form
{
header: [foo, bar, foobar...],
data:[[foo, bar, footer], [foo2, bar2, foobar2], ...]
}
You cannot use a dash in an identifier in v-for. Try
<th v-for="headItem in header" v-text="headItem"></th>
Dash isn't a valid character for any JavaScript variable.

Issue in Spring MVC serving static resources

I am running the Spring application with JQuery. But the application is not running. After the JQuery function is called the application is not working. For example please refer the below image, the alert('name') after the $('#name').val(); is not working.
Can any one please tell why it is not working?
I have added the JQuery file in js folder in WebContent.
And for importing the jquery i used the
<script src="/AjaxWithSpringMVC2Annotation/js/jquery.js"></script>
in JSP page.
Here's the full JSP source:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Users using ajax</title>
<script src="/AjaxWithSpringMVC2Annotation/js/jquery.js"></script>
<script type="text/javascript">
function doAjaxPost() {
// get the form values
alert('doAjaxPost ');
var name = $('#name').val();
alert('name ');
var education = $('#education').val();
alert('education ');
$.ajax({
type : "POST",
url : "/AjaxWithSpringMVC2Annotation/AddUser.htm",
data : "name=" + name + "&education=" + education,
success : function(response) {
// we have the response
$('#info').html(response);
$('#name').val('');
$('#education').val('');
},
error : function(e) {
alert('Error: ' + e);
}
});
}
</script>
</head>
<body>
<h1>Add Users using Ajax ........</h1>
<table>
<tr>
<td>Enter your name :</td>
<td><input type="text" id="name"><br /></td>
</tr>
<tr>
<td>Education :</td>
<td><input type="text" id="education"><br /></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="Add Users"
onclick="doAjaxPost()"><br /></td>
</tr>
<tr>
<td colspan="2"><div id="info" style="color: green;"></div></td>
</tr>
</table>
<a href="/AjaxWithSpringMVC2Annotation/showUsers.htm">Show All
Users</a>
</body>
</html>
You might want to add a resource handler for the path js/**. See 17.15.6 Configuring Serving of Resources.
#Configuration
#EnableWebMvc
public class SpringConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
}
or in XML:
<mvc:resources mapping="/js/**" location="/js/"/>

mvc 3 - ajax.begin form and partial view on httppost

I have a problem with partialView, cant load parital view after post with Ajax.PostBack. When i click submit button a partialView render as View not as a partial. This is my controller:
[HttpPost]
public PartialViewResult UpdatePersonalData(UserLine user)
{
var usr = um.GetUserByLoginMapper(User.Identity.Name);
ViewBag.Regions = rm.GetAllRegionsMapper().ToList();
if (ModelState.IsValid)
{
return PartialView("getLabelsPersonalData", usr);
}
return PartialView("getPersonalData", user);
}
public PartialViewResult getPersonalData()
{
ViewBag.Regions = rm.GetAllRegionsMapper().ToList();
var user = um.GetUserByLoginMapper(User.Identity.Name);
return PartialView("getPersonalData", user);
}
public PartialViewResult getLabelsPersonalData()
{
var user = um.GetUserByLoginMapper(User.Identity.Name);
return PartialView("getLabelsPersonalData", user);
}
getPersonalData.cshtml - partialView
#model MasterProject.JobForYouFinal.BO.UserLine
#using (Ajax.BeginForm("UpdatePersonalData", new AjaxOptions
{
UpdateTargetId = "personalDataContent",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST"
}))
{
<table style="text-align:center; margin:0 auto;">
<tr>
<td>#Html.LabelFor(a => a.PersonalData.Name)</td>
<td>#Html.EditorFor(a => a.PersonalData.Name)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.PersonalData.LastName)</td>
<td>#Html.EditorFor(a => a.PersonalData.LastName)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.Address.PostCode)</td>
<td>#Html.EditorFor(a => a.Address.PostCode)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.PersonalData.KeyWord)</td>
<td>#Html.EditorFor(a => a.PersonalData.KeyWord)</td>
</tr>
<tr>
<td><input id="save" type="submit" value="Zapisz" /></td>
<td>#Ajax.ActionLink("Anuluj", "getLabelsPersonalData", new AjaxOptions {
UpdateTargetId = "personalDataContent",
InsertionMode = InsertionMode.Replace
})</td>
</tr>
<tr>
<td>#Html.ValidationSummary()</td>
</tr>
</table>
}
getLabelPersonalData.cshtml - partialView
#model MasterProject.JobForYouFinal.BO.UserLine
<table class="myAccountTable">
<tr>
<td>#Html.LabelFor(a => a.RegistrationDate)</td>
<td>#Html.DisplayFor(a => a.RegistrationDate)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.PersonalData.Name)</td>
<td>#Html.DisplayFor(a => a.PersonalData.Name)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.PersonalData.LastName)</td>
<td>#Html.DisplayFor(a => a.PersonalData.LastName)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.PersonalData.KeyWord)</td>
<td>#Html.DisplayFor(a => a.PersonalData.KeyWord)</td>
</tr>
<tr>
<td colspan="2"><input id="personalDataButton" type="submit" value="Edytuj" /></td>
</tr>
</table>
index.cshtml = glowny widok
<div class="empAccountSectionContainer">
<div id="personalDataHeader" class="empAccountSectionHeader">Dane personalne</div>
#using (Ajax.BeginForm("getPersonalData", new AjaxOptions
{
UpdateTargetId = "personalDataContent",
InsertionMode = InsertionMode.Replace
}))
{
<div id="personalDataContent" class="empAccountSectionBody">
#{Html.RenderPartial("getLabelsPersonalData", Model.User);}
</div>
}
</div>
Trying fix this issue with some onSuccess function:
<script type="text/javascript">
function onSuccess() {
$('#personalDataContent').load('EmployeeAccount/getLabelsPersonalData');
}
</script>
this is my layout imports
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/themes/start/jquery-ui.css" rel='stylesheet' type='text/css'>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js"></script>
<script str="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-1.7-development-only.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.11/jquery-ui.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmplPlus.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js"></script>
<script str="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/additional-methods.min.js"></script>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/Styles.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery-ui-1.8.22.custom.css")" rel="Stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery.ui.dialog.css")" rel="Stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery.ui.theme.css")" rel="Stylesheet" type="text/css" />
</head>
I had to pust this:
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
in my partialView, becouse validation not worked. Now validation working fine, but when model is valid, cant load partial view as partial.
But still no results. Please help.
I know this is an old question, but I had the same problem. I solved it using the code belowe in my view:
#{
Layout = Request.IsAjaxRequest()?null:"~/Views/Shared/Layout.cshtml";
}
I don't know if this solution is the best one, but it surely works ;-)

Resources