Update a table in thymeleaf without page refresh - javascript

JS code:
<script type="text/javascript" th:inline="javascript">
var senderLogin = [[${senderLogin}]]
var recipientLogin = [[${recipientLogin}]]
function CheckAndGetMessage() {
$.ajax({
type : "GET",
url: '/get_updated_dialog',
data: {'senderLogin':senderLogin, 'recipientLogin':recipientLogin },
success: function (messageList) {
document.getElementById("messageList_local").value = messageList;
$('#message_table').DataTable().ajax.reload();
return;
}
});
};
setInterval(CheckAndGetMessage,1000);
Java code:
#RequestMapping(value = "/get_updated_dialog",method = RequestMethod.GET)
#ResponseBody
public List<Message> getUpdatedDialog(Authentication authentication, #RequestParam("senderLogin") String senderLogin, #RequestParam("recipientLogin") String recipientLogin, Model model){
List<Message> messageList = messageService.UpdatedDialogBetweenUsers( recipientLogin, senderLogin,authentication, model);
return messageList; }
Another Java code:
model.addAttribute("messageList", messageList);
(Attribute is adding in function which returns a view with table page)
My table:
<div id="messageList_local" th:with="messageList_local=${messageList}">
<table id="message_table" cellspacing="0" cellpadding="0">
<span th:each="message : ${messageList}"> <!-- close tags and etc -->
I tried to call this in JS:
document.getElementById("messageList_local").value = messageList;
$('#message_table').DataTable().ajax.reload();
But my table did not refresh. P.S. I checked with debugger that getUpdatedDialog returns a list with updated messages.

Related

public action method was not found on the controller

I'm getting an error that my Action Method was not found, but can't figure out what's wrong. I searched the internet now for hours but haven't found a solution till now.
In my View I have a JavaScript function:
<script type="text/javascript">
function ShowHideAds(button) {
var dAds = document.getElementById("dAds");
if (dAds.style.display == "none") {
dAds.style.display = "block"
var txtBox = "Visible";
$.post('#Html.Action("GetState","Rights")', { txtAds: txtBox });
}
else {
dAds.style.display = "none"
var txtBox = "Hidden";
$.post('#Html.Action("GetState", "Rights")', { txtAds: txtBox });
}
} </script>
I'm switching between a Textbox and a Listbox and depending on which is visible, I want to pass the parameter to my method.
My method in my Controller is the following:
[HttpPost, ActionName("GetState")]
public ActionResult GetState(string txtAds, string txtRg)
{
if (txtAds != null)
stateTxtAds = txtAds;
if (txtRg != null)
stateTxtRg = txtRg;
return View();
}
and finally here is my routing:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Before using the #Html.Action() method I had following line of code:
$.post("/Rights/GetState", { txtAds: txtBox });
but this did not work when the project was deployed so I tried to use the #Html.Action two send my variables to my controller method.
Can anyone help please?
Thank you!
GetState(string txtAds, string txtRg) has two parameters but you are only providing one. If you want it to accept two but only provide it one like you are doing in the call, do the following.
For example for the post #Html.Action("GetState", "Rights")', { txtAds: txtBox }:
GetState(string txtAds, string txtRg = "")
This way you can just send txtAds if you want and it should reach it.
The ajax I would recommend:
var json = '{txtAds: "' + txtAds + '"}'
$.ajax({
url:'#Url.Action("GetState", "Rights")',
type:'POST',
data: json,
contentType: 'Application/json',
success: function(result){
// Whatever you want to do next.
}
})

jQuery Ajax call doesn't work with me at any cost in MVC 4

I have a view that contains a dropdown and when I select a particular option I want to display the data returned in a partial view. At any cost the ajax function is not working. I am using VS 2013 MVC 4.
Tried to change the latest jquery from http://code.jquery.com/jquery-latest.min.js but still doesn't work. Ajax call are not working that is it. Breaking my head from last 1 day.
View:
#model IEnumerable<TTracking.CareWebService.ClinicGroup>
#using System.Globalization;
#{
ViewBag.Title = "Appointment";
Layout = "~/Views/Shared/_LayoutWebsite.cshtml";
}
<h2></h2>
<script type="text/javascript">
$(function () {
$("#CategoryID").change( function (event) {
var userId = $(this).val();
$.ajax({
url: "#Url.Action("GetDoctors", "Controller")",
data: { id : userId },
type: "GET",
dataType: "html",
success: function (data) {
$("#divPartialView").html( data );
}
});
});
});
</script>
<div class="dropdown">
#Html.DropDownList("CategoryID",
(List<SelectListItem>)ViewBag.Categories, "Select Clinic")
</div>
<div id="divPartialView">
</div>
Controller that returns Partial View:
public PartialViewResult GetDoctors(int id)
{
var res = new CWS.DoctorsCollection();
try
{
CWS.CWSSoapClient cl = new
CWS.CWSSoapClient();
res = cl.getDoctorsByClinicGroup(id.ToString(),
"sercuritykey");
}
catch (Exception ex)
{
}
return PartialView("DoctorsList",res.Doctors);
}

How can I pass an element as a parameter

I have the following code:
#Html.PagedListPager(Model, page => Url.Action("Index", new {from = ? , to = ? , page}))
And this is my Action method:
public ActionResult Index(string from, string to, int? page)
{
}
I want to specify the from and to parameters that comes from a picker which are defined as below:
#Html.EditorFor(c => c.LastOrDefault().Date, "MyPickerTemplate")
#Html.EditorFor(c => c.FirstOrDefault().Date, "MyPickerTemplate")
How can I send the value of the EditorFor's as a parameter to Url.Action? I can find them with javaScript like below:
var from = document.GetElementByClassName("date")[0].value;
var to = document.GetElementByClassName("date")[1].value;
But I don't know how should I send them as parameter to Url.Action.
var from = document.GetElementByClassName("date")[0].value;
var to = document.GetElementByClassName("date")[1].value;
Now you have two parameters. You can call ajax function as below.
$.ajax({
url: "/Controller/TheAction",
type: "get",
data: { fromParam: from, toParam: to }
});
Here is the controller,
public ActionResult TheAction(DateTime fromParam, DateTime toParam)
{
// your code.
}
EDIT:
You must call ajax from pager button click. For that, do following.
<div id="myPager">
#Html.PagedListPager(Model, Page => "")
</div>
<script type="text/javascript">
$(function () {
$('#myPager').on('click', 'a', function () {
var currentPage = $(this);
// ajax call
});
});
</script>

How to Pass id value of actionlink to javascript function in my Asp.net Mvc Project

I have a table for departments. Right now I created controller for every department and every department have index.cshtml.
But they use the same functions. I hard coded their departmentId in every index page.
for example for department IT with departmentId = 1
public class ItController : Controller
{
// GET: It
public ActionResult Index()
{
return View();
}
}
And in It's index page I have hard coded with decleration var id = 1; Like this
<div class="panel panel-body">
<div class="col-md-4 table-responsive" id="productsTable"></div>
</div>
<script type="text/javascript">
var id = 1; // for the department that id is 1 so I have to create index for every department and hard code like this
function AllProductsByDepartmentId(id) {
var tbl = $('#productsTable');
$.ajax({
cache: false,
url: '/Home/GetAllProductsByDepartmentId?id=' + id,
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html',
success: function (result) {
tbl.empty().append(result);
},
error: function () {
}
});
}
</script>
But to do like this is not good becouse if by some reasen changes Id of department or when I create a new department next time then
I have to hard coded again ...
What I want is first I want to populate those departments in my _Layout dynamicaly from database.
So I created controller
public class DepartmentsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Departments
public async Task<ActionResult> Index()
{
return View(await db.Departments.ToListAsync());
}
}
And this is my PartialView of Departments and I want to populate it in _Layout.cshtml, but I don't know how to do and how to link them to a function ...
#model IEnumerable<Inventory.Models.Departments>
#foreach (var item in Model) {
#Html.ActionLink(modelItem => item.DepartmentName???????, ??????, ?????, new { id = item.DepartmentId })
}
and link them to this java function
function AllProductsByDepartmentId(id)
{
// ......
}
I think I have to create another common controller to have an index page to all departments.But How to create actionlinks dynamicaly and link them to javascript function. Thank you in advance!
There is no need to use #Html.ActionLink() to generate links in this case. You foreach loop can be just
#foreach (var item in Model) {
#item.DepartmentName
}
Note that the value of DepartmentId is added to the link as a data attribute.
Then you script would be
var url = '#Url.Action("GetAllProductsByDepartmentId", "Home")';
var tbl = $('#productsTable');
$('.details').click(function() {
tbl.load(url, { id: $(this).data('id') });
});

Ajax replace new arraylist without refresh page

I am new ajax, how can i replace ${phList} with new arraylist so that ajax can help me update the content without refresh whole page.
The ajax will trigger controller to retrieve data and store in arraylist then pass the arraylist to ajax. Ajax will update the content in jsp. Next step forEach loop will generate the column and checkbox with value if there have record retrieve from database.
Any solution and hope this solution can help others. Thanks!
myJsp.jsp
<select id="selected_year" name="selected_year" class="form-control">
<c:forEach var="line" items="${yearlist}">
<c:choose>
<c:when test="${refreshInd ge 0 and line eq refreshInd}">
<option selected="selected"><c:out value="${line}" />
</option>
</c:when>
<c:otherwise>
<option><c:out value="${line}" /></option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
<div class="row">
<div class="col-md-4">
<form:input path="phList[${PHstatus.index}].holidayDesc" class="form-control col-md-5" value="${ph.holidayDesc}" />
</div>
<div class="col-md-3">
<form:input path="phList[${PHstatus.index}].startDate" class="form-control" value="${ph.startDate}" id="calendar1" placeholder="dd/mm/yyyy" onkeypress="return noAlphabet(event)" />
</div>
<div class="col-md-3">
<form:input path="phList[${PHstatus.index}].endDate" class="form-control" value="${ph.endDate}" id="calendar2" placeholder="dd/mm/yyyy" onkeypress="return noAlphabet(event)" />
</div>
<div class="col-md-2">
<form:checkbox path="phList[${PHstatus.index}].checkboxDel" value="" class="cbposition" />
</div>
</div>
<br>
</c:forEach>
After i change selected_year to trigger the ajax, it work well but :success function(response) cannot work. I want to remove the existing ${phList} and update with new arraylist by replace ${phList} show at above jsp.
myJavascript.js
$(function($) {
$("#selected_year").change(function(){
var selectedText = $(this).find("option:selected").text();
var $form = $(this);
var action = $form.find('.send').val();
var list[];
var array[];
$.ajax("holiday/pubholiday.json?" , {
method: "GET",
accepts: "application/json",
dataType: "json",
data: $form.serialize() + '&selectedText=' + selectedText,
success: function(response) {
$("#phList").remove()
$(JSON.stringify(response))
//how to pass the response which is my new arraylist to replace the ${phList}
},
}).done(function(data) {
console.log(data)
alert("Data Sent" + selectedText)
})
.fail(function(jqXHR, textStatus, errorThrown) {
var errorMessage = "";
if (jqXHR.status == 401) {
errorMessage = "Your session has expired. Please login again.";
}else if(jqXHR.status == 500){
console.log(jqXHR.status);
console.log(jqXHR.responseText);
console.log(thrownError);
}else {
try {
var errorJson = JSON.parse(jqXHR.responseText);
errorMessage = errorJson.error;
} catch (e) {
errorMessage = errorThrown || textStatus;
}
}
});
})
});
This is object model store in the arraylist. Each record will contain object model data.
model.java
public class PubHoliday {
private int year;
private String holidayID;
private String holidayDesc;
private String startDate;
private String endDate;
private boolean checkboxDel;
private String selected_year;
private int refreshInd;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getHolidayID() {
return holidayID;
}
public void setHolidayID(String holidayID) {
this.holidayID = holidayID;
}
public String getHolidayDesc() {
return holidayDesc;
}
public void setHolidayDesc(String holidayDesc) {
this.holidayDesc = holidayDesc;
}
public String getStartDate() {
return startDate;
}
public String getEndDate() {
return endDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public boolean getCheckboxDel() {
return checkboxDel;
}
public void setCheckboxDel(boolean checkboxDel) {
this.checkboxDel = checkboxDel;
}
public String getSelected_year() {
return selected_year;
}
public void setSelected_year(String selected_year) {
this.selected_year = selected_year;
}
public int getRefreshInd() {
return refreshInd;
}
public void setRefreshInd(int refreshInd) {
this.refreshInd = refreshInd;
}
}
First, you need to wrapper <c:forEach var="ph" items="${phList}" varStatus="PHstatus"> by div with id, example:
<div id="list_holidays">
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
.......
</c:forEach>
</div>
Then in success ajax code
- Empty div#list_holidays
- Get result, each row, create new div, append to div#list_holidays
success: function(response) {
var wrapper = $('#list_holidays');
wrapper.html('');
//->foreach response result
// -> $('div').html(your template).appendTo(wrapper)
}
JSP is server side rendering. meaning, when a request is received server uses the variable ${phList} to render a dynamic HTML page and sends that page to the browser. Ajax is a request made by your javascript sitting in browser. So, the browser has no way of knowing or changing the variable $(phList} directly and affecting the template.
However, what you said can be achieved. In one of following ways
Method 1 (easiest):
Implement holiday/pubholiday.asp which responds with only this instead of json.
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
<div class="row">
<div class="col-md-4">
<form:input path="phList[${PHstatus.index}].holidayDesc" class="form-control col-md-5" value="${ph.holidayDesc}" />
</div>
...
<br>
</c:forEach>
Add a container element to the array items something like this
<div id="container" >
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
...
</c:forEach>
</div>
Change your ajax request in main page to this. When you get a response from pubholiday.jsp, replace contents of #container to what is received from ajax.
...
$.ajax("holiday/pubholiday.asp?" , {
method: "GET",
accepts: "application/html",
dataType: "json",
data: $form.serialize() + '&selectedText=' + selectedText,
success: function(response) {
// This is where magic happens
$("#container").html(response);
},
}).done(function(data) {
console.log(data)
alert("Data Sent" + selectedText)
})
...
Method 2:
If you need the response to be only json, in success callback read the json, and generate html yourself by concatenating strings and then replace the #container element.
Method 3 (recommended):
User some client side rendering library like polymer or handlebars to render json into html.

Categories

Resources