How can refresh the page every minute with ajax? - asp.net

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/

Related

How do I write my ajax code to move from razor view to another?

In my Save button ajax code I'm looking to redirect back to another razor page if a successful save occured. How would I do that?
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/StorageRequests/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
alert('Thank you for your delivery time!');
}
},
error: function () {
alert('Failed');
}
})
You can use window.location.href
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
window.location.href='/{your razor page url relative to website root}';
}

Retrive data at real time after specific time interval by SignalR

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()

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;
});
});

Ajax success when a view is returned

I'm struggling to return a view or partial view with Ajax. Whenever I change the return type to something that isn't JSon the ajax command never succeeds. I need to return a partial view because I want to return a lot of data back.
This is my current code:
(Controller)
[HttpPost]
public ActionResult AjaxTestController(string Input)
{
string Results = Input + " -- TestTestTest";
return PartialView("Test", Results);
//return new JsonResult() { };
}
(View)
function AjaxTest() {
alert("test");
$.ajax({
type: "POST",
url: "Home/AjaxTestController",
data: "Input=Test11111",
success: function () {
alert("Success!");
}
});
Thanks!
You can use the $.post command for that:
function AjaxTest() {
alert("test");
$.post({
url: "Home/AjaxTestController",
data: "Input=Test11111",
success: function (response) {
alert(response);
}
});
try the following:
$(function () {
$('#submit').live('click', function () {
AjaxTest();
});
});
function AjaxTest() {
$.ajax({
type: "POST",
url: '#Url.Action("AjaxTestController", "Home")',
data: { Input: "Test - " + new Date() },
success: function (data) {
$('#partialResult').html(data);
},
error: function (xhr, err) {
alert(xhr.responseText);
}
});
};
inside your view and ensure that you have your target div set up for the partial to be populated into:
<div id="partialResult"></div>
also, for the example above, I added a button to the view to initiate the ajax (purely for testing):
<input type="button" value="Submit" id="submit" />
your 'partialview' should look something like this:
#model string
<h2>
Partial Test</h2>
<p>
#Model
</p>
no other changes are required to the existing action for this to now function as required.
[UPDATE] - I changed the AjaxTest() method to include the error event (the result of which is captured in an alert). hopefully, this may help further.
partial View is different than view you have to specify the whole path to the partial view or have it in share folder. otherwise is going to return not found and never success. any way this always work for me, try
partialView("~/Views/ControllerView/Test.cshtml")

Fire a controller action from a jQuery Autocomplete selection

I have a jQuery autoselect box displaying the correct data. Now I would like to fire an ASP.NET MVC 3 controller when an item is selected. The controller should then redirect to a View. Here's my jQuery autocomplete code (I'm sure something is missing in the 2nd Ajax call, but I haven't found it yet):
<script type="text/javascript">
$(function () {
$("#Client").autocomplete({
source: function (request, response) {
$.ajax({
url: 'Entity/GetClientAutoComplete', type: 'POST', dataType: 'json',
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item, value: item };
}))
}
})
},
minLength: 1,
select: function (event, ui) {
$.ajax({
url: 'Entity/GetApplicationsByName/' + ui.item.value, type: 'POST'
})
}
});
});
</script>
And here's the controller I'm trying to call:
public ActionResult GetApplicationsByName(string id)
{
ViewBag.Client = id;
var apps = _service.GetDashboardByName(id);
return View("Dashboard", apps.ToList());
}
When I watch the Ajax call fire in Firebug, I see the correct URL configuration, but nothing else happens. It's acting as though it wants to load something rather than send something. I'm confused. Thank you for any guidance.
Well you sent an id by POST to the GetApplicationsByName controller and the controller is sending back the view.
If you want redirection, you can use the following:
select: function (event, ui) {
window.location.href = 'Entity/GetApplicationsByName/' + ui.item.value;
}

Resources