Retrive data at real time after specific time interval by SignalR - asp.net

I have page which contains three panels for employee attendence, salary, production. I have to update the panels at real time by SignalR.
My hub class
public class MessagesHub : Hub
{
private string ConnectionString = ConfigurationManager.ConnectionStrings["database"].ToString();
[HubMethodName("sendMessages")]
public void SendMessages()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
context.Clients.All.updateMessages();
}
}
In Controller
public ActionResult Panels()
{
...code..
return Partial("_panelData", model);
}
The partial page has the panels along with data to display.
In the main View page(Panels), at script tag
<script>
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.messagesHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getData()
};
// Start the connection.
$.connection.hub.start().done(function () {
getData();
}).fail(function (e) {
alert(e);
});
});
function getData() {
$.ajax({
url: '/PanelController/Panels',
type: 'GET',
dataType: 'html'
}).success(function (result) {
$('.panel').html(result)
}).error(function () {
window.console.log("failure");
});
}
</script>
It works fine when the page loads. But i also want it to load the data at every 1 min time interval.
Thanks in advance

Maybe I missunderstood but for me SignalR is useless there. Something like this should work :
$(function() {
getData();
});
function getData() {
$.ajax({
url: '/PanelController/Panels',
type: 'GET',
dataType: 'html'
}).success(function(result) {
$('.panel').html(result)
window.setTimeout(getData(), 60000)
}).error(function() {
window.console.log("failure");
});
}
If you want to keep signalr the only things to do is to add this:
window.setTimeout(getData(), 60000) inside the callback of the getData function()

Related

How can refresh the page every minute with ajax?

I want to update a div with the minute of the match on my page every 15 seconds. How can i do that ? I just want to refresh the area where that div is.
<script>
setInterval(function () {
$.ajax({
#*url: '#Url.Action("_List", "Home",new { match_id=Model.match.match_id})',*#
cache: false,
success: function (result) {
$("#test").html(result);
console.log(result)
//alert(result);
}
});
}, 20000);
</script>
Use partial views for this. They will allow you to update only a part of the DOM without having to perform a full page refresh or a postback and they are strongly typed.
For example I created below partial view
function loadPartialView() {
$.ajax({
url: "#Url.Action("ActionName", "ControllerName")",
type: 'GET', // <-- make a async request by GET
dataType: 'html', // <-- to expect an html response
success: function(result) {
$('#YourDiv').html(result);
}
});
}
$(function() {
loadPartialView(); // first time
// re-call the function each 5 seconds
window.setInterval("loadPartialView()", 5000);
});
After every 5 seconds it goes to controller and executes the action
public class ControllerName: Controller
{
public ActionResult ActionName()
{
.
. // code for update object
.
return PartialView("PartialViewName", updatedObject);
}
}
For more information
https://cmatskas.com/update-an-mvc-partial-view-with-ajax/

Send string from View to Controller ASP.Net mvc

So we are pretty new to ASP.Net MVC
We have this method that runs when we click on a button in our view. We would like to send the date string to our controller. How can we achieve this?
$('#calendar').fullCalendar({
//weekends : false
dayClick: function(date) {
console.log(date.format());
}
})
This is our controller
[HttpPost]
public IActionResult Booking(string test)
{
var booking = new Booking();
//booking.Date = dateTime;
Console.WriteLine(test);
var viewModel = new BookingsideViewModel
{
Subjects = new[] {"Matematik", "Dansk", "Engelsk"},
Booking = booking
};
return View();
}
you can do it using ajax call,
$.ajax({
url: '#Url.Action("Booking")',
data: { 'test' : date },
type: "post",
cache: false,
success: function (response) {
console.log("success");
},
error: function (error) {
console.log(error.message);
}
});
you can also write url like this:
url:"/ControllerName/ActionName"

View not loaded when ActionResult is called from AJAX in ASP.NET MVC

I have called actionresult function from JavaScript using AJAX when a button is clicked:
<script type="text/javascript">
$('.btn-SelectStudent').on('click', function () {
$('input:radio').each(function () {
if ($(this).is(':checked')) {
var id = $(this).val();
$.ajax({
url: '#Url.Action("ParseSearchLists", "Upload")',
data: { studentId: id }
}).success(function (data) {
alert('success');
});
}
else {
// Or an unchecked one here...
}
});
return false;
})
</script>
Inside the UploadController.cs:
[HttpPost]
public ActionResult ParseSearchLists(int studentId)
{
SearchModel searchModel = ApplicationVariables.searchResults.Where(x => x.StudentId == studentId).ToList().First();
TempData["SearchModel"] = searchModel;
return RedirectToAction("UploadFile", "Upload");
}
public ActionResult UploadFile()
{
searchModel = TempData["SearchModel"] as SearchModel;
return View(searchModel); //debug point hits here.
}
Inside UploadFile(), I have returned View and it should load another view. But I get only "success" in alert but no new view is loaded. I assume, view should be loaded.
You're making an "AJAX" call to the server, meaning your request is running outside of the current page request and the results will be returned to your success continuation routine, not to the browser's rendering engine. Essentially the data parameter of that routine is probably the entire HTML response of your UploadFile view.
This is not what .ajax is used for. It is for making asynchronous requests to the server and returning data (usually JSON or XML) to your javascript to be evaluated and displayed on the page (this is the most common use anyway).
I can't see your HTML, but wouldn't you be better off just using an <a> anchor (link) tag and sending your student ID on the query string? It's hard to tell what you are attempting to do but your views' HTML (.cshtml) will never be displayed using the code you have now.
It seems, you are not loading view returned to div on ajax success. replace #divname with your div in your code in below code. i hope this helps to resolve your issue
<script type="text/javascript">
$('.btn-SelectStudent').on('click', function () {
$('input:radio').each(function () {
if ($(this).is(':checked')) {
var id = $(this).val();
$.ajax({
url: '#Url.Action("ParseSearchLists", "Upload")',
dataType: "html",
data: { studentId: id }
}).success(function (data) {
$('#divName').html(data); // note replace divname with your actual divname
});
}
else {
// Or an unchecked one here...
}
});
return false;
})
</script>
[HttpPost]
public ActionResult ParseSearchLists(int studentId)
{
SearchModel searchModel = ApplicationVariables.searchResults.Where(x => x.StudentId == studentId).ToList().First();
return View("UploadFile",searchModel); //debug point hits here.
}

Calling asp.net server function using jquery ajax

Am basically new to jquery. I have a function in aspx code bihind. I need to call it in a button click from aspx page using jquery. The server side function takes no arguement and returns no data.
The function the code behind is :
[WebMethod]
public void BindTreeview()
{
TreeView1.Nodes.Clear();
System.IO.DirectoryInfo RootDir = new System.IO.DirectoryInfo(#"C:\ClientDocuments\Ford Retail Ltd\");
// output the directory into a node
TreeNode RootNode = OutputDirectory(RootDir, null);
// add the output to the tree
TreeView1.Nodes.Add(RootNode);
//TreeView1.SelectedValue = hdnSelectedNode.Value;
if (hdnSelectedNode.Value != string.Empty)
{
TreeView1.CollapseAll();
TreeNode searchNode = TreeView1.FindNode("Electricity");
if (searchNode != null)
searchNode.Expand();
}
}
aspx jquery is
$(document).ready(function () {
$('#btnNewFolder').click(function () {
// alert('Clicked');
$.ajax({
url: 'Default.aspx/BindTreeview',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert(1);
},
error: function (result) {
alert("The call to the server side failed. " + result.responseText);
}
});
});
});
When i run appln am getting alert on result.responseText. Where am i getting wrong? Quick response will be highly appreciable.
mark your method as static
public static void BindTreeview()

Extract Div from returned view

I an working on returning view from controller to jquery ,View is returned but i want to extract div from returned view.My Current code is like this
public ActionResult DeleteItem(int pid)
{
//my logic goes here
retutn View("SomeView",model);
}
Jquery
enter code here
script type="text/javascript">
$(document).ready(function () {
$('.Remove').click(function () {
var value = $(this).attr('id');
$.ajax({
cache:true,
type: "POST",
url: "#(Url.Action("DeleteItem", "ControllerName"))",
data: "pid=" + value,
success: function (data) {
$("body").html(data);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to subscribe.');
},
complete: function() { }
});
return false;
});
});
</script>
My current logic returns view and assign total view i.e html+body to body part of page ,which shows html part two times.Is there any way to retrieve div from the returned view and reload it.
thanx in advance
Your controller action should return a PartialViewResult otherwise it will return your layout page in the response. If you want to cater for both scenarios you can check whether the request is an AJAX request:
public ActionResult DeleteItem(int id) {
// delete your item
if (Request.IsAjaxRequest()) {
// return just the partial view
return PartialView("yourview");
}
// otherwise handle normally
return RedirectToAction("list");
}
To understand the difference between returning View and returning PartialView please see What's the difference between "return View()" and "return PartialView()".
script type="text/javascript">
$(document).ready(function () {
$('.Remove').click(function () {
var value = $(this).attr('id');
$.ajax({
cache:true,
type: "POST",
url: "#(Url.Action("DeleteItem", "ControllerName"))",
data: "pid=" + value,
success: function (data) {
var t=$(data).find('.divtoreplacewith');
$('.divtoreplace').replaceWith(d);
//Wasted my 2 days for above two lines.But satisfied with solution,
//Both div are same but '.divtoreplacewith' is having new data,And I have replaced div with that div that's all
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to subscribe.');
},
complete: function() { }
});
return false;
});
});

Resources