I'm using asp.net MVC3 for a website that displays in a view a query result (managed in the controller) using a foreach.
What I want to do now is to automatically refresh the output of the query every tot time, without refreshing the page.
How can I do that using ajax?
This is the code of the View:
#{
string firstTime = "";
}
#foreach( var database in Model)
{
if (!(firstTime == database.DB))
{
<h3> #database.DB </h3>
}
<div class="logContainer" onclick="location.href='/logs/Details?databaseID=#database.DB&exceptionName=#database.Exception&exceptionsOccurred=#database.Count';">
<div class="counter"><b>#database.Count</b></div>
<div class="exceptionName"> Exceptions of Type: #database.Exception</div>
<div class="date">Siste: #database.LastOccurred</div>
</div>
<hr />
firstTime = database.DB;
}
You could use the window.setInterval javascript method to send AJAX requests to the server at regular intervals and refresh the corresponding part of the DOM. For example if you wanted to refresh the contents every 10 seconds:
window.setInterval(function() {
$.post('#Url.Action("someaction", "somecontroller")', function(result) {
$('#results').html(result);
});
}, 10 * 1000);
This will send an AJAX request to the controller action which in turn could return a partial view containing the updated results:
pubilc ActionResult SomeAction()
{
SomeViewModel model = ...
return PartialView(model);
}
The result of this partial view will then be injected into some DOM element with id="results".
You could either pass the query result using JSON and render the HTML yourself from javascript, or separate the for-each code to a different partial view, and using jQuery's $.ajax method change the query result's div html with the new response
Why not put your data in to an existing grid control such as DataTables, which is lightweight pretty fast and extensible. Then, using a javascript timer, tell the data table to refresh it's contents.
I've used this with MVC3 with great effect.
Related
What would be the best method to transfer data from one view to another view? or is this bad practice?
The reason is that i want to display #model.count() from one view to the homepage, basically a summary of all the views on the homepage. There is tempdata, html.helper etc but id like to know the best and most reliable method. Thus avoiding problems further on down the line
here is the code in question
product.cshtml
<p>Total amount of Products = #Model.Count()</p>
i basically want that same value to display on the homepage
You'd have to refresh the homepage for the value to actually 'update.' At that point you may as well pass the value back in as a parameter, but I think that's not what you're hoping for.
It probably isn't the cleanest solution, but I would think you'd want your text on the main page to be settable via some javascript/jquery.
Main Page has this snippet:
<form id="PassBackVals"
<input type="hidden" name="ProductCount" value="0">
</form>
<script>$( ".ProductCount" ).change(function() {
$("$CurrentProductCount").text = $(".ProductCount").val;
});
</script>
and the Area displaying the text itself on the main would have something along the lines of
<p> I'm currently showing <div id="CurrentProductCount">0</div> Products </p>
Then in your product.cshtml, you'd have
<script>$(".ProductCount").val = #Model.Count()
$( ".ProductCount" ).change();
</script>
Ok i looked into other methods and resolved the issue by moving the code behind the viewbag into a public method below
[OutputCache(NoStore = true, Location = OutputCacheLocation.Client, Duration = 10)]
public ActionResult UpdateTotals()
{
JobController j = new JobController();
ViewBag.JobCount = j.JobCount();
ProductController p = new ProductController();
ViewBag.ProductCount = p.ProductCount();
return PartialView("UpdateTotals");
}
then i added the viewbags into a partial view and using setinterval() javascript,
<div id ="UpdateTotals">
#{ Html.RenderAction("UpdateTotals");}
</div>
<script>
setInterval("$('#UpdateTotals').load('/home/UpdateTotals')", 10000);
</script>
i was able to refresh the data constantly to my desire without the mess of pulling data through views via javascript.
hopefully this will help anyone in future :)
I am using highcharts. Some of my charts needs heavy calculations that would need about 1 minute to complete. As you know in highcharts we make our charts as a model and pass it to our view. I want that the view be loaded and show a loading picture and when the background calculation is done receive the model and show the charts.
Means I want my view be shown but also be await to receive a model.
How to handle this in asp.net mvc4 and c#?
Or any other ways...?
Here is what i'd prefer,
Highcharts provides an option to show loading.
can be done with options provided in
options in api provided here
you can use showLoading() and hideLoading() methods to dynamically show and hide the test.
so you can start the loading indicator when the calculations initiate and then hide it after displaying the chart
here is a example which I hope would work for you.
My solution is this:
In my view I check that is the model null or not.
If the model be null I will send an ajax request to a method in my controller to calculate.
While this is going I am showing a page whith a div containing Please wait,Loadin... message.
Then the calculation method saved the calculation result in a TempDate and in success function I will refresh the view.
In the controller for this view I will pass the TempDate to the view.
public ActionResult Chart()
{
var chart=TempData["chart"];
return View(chart);
}
Chart view:
#model DotNet.Highcharts.Highcharts
<script src="~/Scripts/jquery-1.8.3.js"></script>
#if (Model != null)
{
<script src="~/Scripts/highcharts.src.js"></script>
#(Model)
}
else
{
<h3 style="text-align:center">Loadin...</h3>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/WebServices/DrawChart",function(){
window.location.replace("/WebServices/ChancePreview");
})
});
</script>
}
And Finally:
public JsonResult DrawChart()
{
//Calculations goes here...
TempData["chart"]=chart;
}
So the design ideal is to have one page with a couple different 'widgets' in this MVC app. Each 'widget' should be able to submit information back to itself and reload only itself. Simple in web forms, not so much with MVC it seems
First, we have our main page controller, nothing special
public ActionResult Index()
{
return View();
}
Next, we have our main page View. Note that I have tried both Action and RenderAction and there is no change in behavior
#Html.Action("Index", "Monitor", new { area = "Statistics" });
<div id="messages">
#Html.Action("Index", "Messages", new { area = "Data"});
</div>
#section Script {
<script src="#Url.Content("~/Scripts/jquery-1.9.1.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$('#filter').click(function () {
$.ajax({
method: 'POST',
url: '#Url.Action("Index", "Messages", new { area = "Data"})',
success: function(data){
$('#messages').html(data);
}
});
return false;
});
</script>
The Index ActionResult in the Messages Controller:
public ActionResult Index()
{
var model = GetMessages();
return PartialView(model);
}
For the sake of brevity, going to skip the whole of Monitor Index View, and only give a brief version of Messages Index View
#using (Html.BeginForm("Index", "Messages", FormMethod.Post))
{
//Some fields to limit results are here, with style classes
<button type="submit" id="filter">Filter</button>
}
#foreach(var item in Model)
{
//Display results
}
Upon loading the main page, all looks good. The fields to limit results are displayed, as well as messages. I can enter something into the fields, click Filter, and am returned to the main page but! ...the fields have lost their style classes and the messages are unfiltered.
Strange, but more strange is if I again enter information in the fields and click Filter, this time I am not taken to the main page, but get only the Partial View of the Messages Index displayed and the messages are not filtered.
I can't say that the filtering not working is related to this issue or not, but the non-consistent behavior of clicking Filter is the part that bothers me. Anyone like to point out what I am doing wrong in here?
You probably should be using Ajax.BeginForm rather than Html.BeginForm in your widgets. That will let the widgets manage their own posts:
<div id="messages">
#using (Ajax.BeginForm("Index", "Messages", new AjaxOptions { UpdateTargetId = "messages" }))
{
// fields content
}
// other widget content
</div>
The "bizarre" behavior you're seeing is happening because on page load the submit event for your #filter button is being hijacked using jQuery, but after the first replacement of the widget content the #filter submit event is no longer being hijacked so when you click it the whole page is submitted. If you don't want to use Ajax.BeginForm you'll need to use $.on rather than $.click to sign up events, as it will handle events for matching elements which are created after the event sign up script has run.
I am using MVC C# along with Jquery.
I have a partial view in a rather large page that has a number of tabs.
On a click of a checkbox, I like to update the partial view WITHIN the form.
What I am getting instead is just the partial view
Here is my code in Jquery:
$('#activelist,#inactivelist').change(function () {
var status = 'inactive';
window.location.href = '#Url.Action("Skits","KitSection")' + '?id=' + id+ '&status=' + status;
});
Any idea on how I could update the partial view within a form in terms of how I would make a call to it?
Here is the code for the PartialView
return PartialView(Kits);
As mentioned, what I see is just the partial view displayed and not the whole form.
window.location.href will reload the entire page. You need to reload some part of your page without a complete reload. We can use jQuery ajax to do this. Let's Find out what jQuery selector you can use to get the Partialview.
For example , Assume your HTML markup is like this in the main form ( view)
<div>
<p>Some content</p>
<div id="myPartialViewContainer">
#Html.Partial("_FeaturedProduct")
</div>
<div>Some other content</div>
</div>
And here the DIV with ID myPartialViewContainer is the Container div which holds the content of the partial view.So we will simply reload the content of that div using jQuery load method
$(function(){
$('#activelist,#inactivelist').change(function () {
var id="someval";
var status = 'inactive';
$("#myPartialViewContainer").load('#Url.Action("Skits","KitSection")' + '?id=' + id+ '&status=' + status)
});
});
You are redirecting the user, via the window.location.href property, to the URL of your partial, hence only displaying that partial.
You should instead do an AJAX call to the partial to retrieve it's HTML and then use something like the .append method to add it to whatever container element you want it to be added to.
EDIT: The .load() jQuery ajax method is actually better for this specific situation.
For the site I'm currently working on, I have a list of products which I need to display in a paged list. The list needs to be used on several different pages, each of which has their own rules for how to retrieve their list of products. The list pages need to refresh with AJAX. I'm using LINQ-2-SQL to talk to the database, and MVC3/Razor as the view engine.
So far so good.
What I need help with is figuring out how to implement this. I'll explain what I've done so far, and what isn't working, and I hope someone can give me some direction of the best way to get this working, whether it be bug fixes, missing options, or a redesign. Note that the setup described above is immutable, but everything else can be altered.
For the first set of data, I have Index.cshtml. This will be a list of all products. There will be other sets (such as a list of all products in a category, but I can do the selection for that just fine), but this is the primary test case.
Currently, I have an object to represent the state of the grid: PagingData. The details of it aren't really important, but it takes an IEnumerable when first instantiated, it stores itself in HttpContext.Current.Session between requests, and it has a function that returns an IEnumerable of the products that are supposed to be on the current page. I tried it as an IQueryable<>, but that didn't work.
Currently, I am getting an IQueryable.ToList() and setting it as the data for a DataPager that's used as the Model of a Partial view called _ProductList.cshtml. _ProductList primarily consists of a pager control (another partial) and a foreach loop across the Model to display a partial for each Product.
_ProductList.cshtml:
#model PagingData
<script type="text/javascript">
$(function() {
$('#productList a.pagerControl').live('click', function() {
$('#productList').load(this.href);
return false;
});
</script>
<div id="productList">
#Html.Partial("_Pager", Model)
#foreach (var item in Model.ProductsOnPage)
{
#Html.Partial("_ProductListGridDetail", item);
}
</div>
_Pager uses: #Html.ActionLink(page.ToString(), "_ProductListSetPage", new { newPage = page }, new { #class = "pagerControl" }) to provide the links to change pages (the page variable is the number of the page to draw, from a loop).
This solution works, kindof. The problem I'm having with it is that the only way to update the PagingData with the new page is via a Controller, and each method of modifying the pager (page, # of products per page, format, sort) will need its own controller because I can't overload them. This also means _Pager produces URLs like http://localhost:52119/Product/_ProductListSetPage?newPage=3 instead of http://localhost:52119/Product.
I've tried Ajax.ActionLink(), and wrapping the whole thing in an Ajax.BeginForm(), but neither seemed to work at all. I do have the jquery.unobtrusive-ajax.js library included.
Is this approach feasible? Should I replace the PagingData object with something else entirely? I do not want the paging data in the URL if it's at all possible to avoid it.
If you don't want the page in the url you could use a <form> instead of link, like this:
#using (Html.BeginForm("Index", "Product")
{
#Html.Hidden("newPage", page)
<input type="submit" value="#page" />
}
Which should generate a form for each page with a hidden field containing the actual page number, for example:
<form action="/Product" method="post">
<input type="newPage" value="3" />
<input type="submit" value="3" />
</form>
Now all that's left is to AJAXify this form:
$(function() {
$('#productList form').live('submit', function() {
$.post(this.action, $(this).serialize(), function(result) {
$('#productList').html(result);
});
return false;
});
});
Which would invoke the Index action on ProductController:
public ActionResult Index(int? newPage)
{
var model = ... fetch the products corresponding to the given page number
return PartialView(model);
}