How to show a loading state before show the complete page? - c#

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

Related

MVC Render section scripts in controller

I would like to render the "scripts" section of the .cshtml view inside the controller as a string. Is this possible?
What I actually want to do is get the scripts with a separate ajax call and then run eval on the script after loading the html of the view also with ajax.
I've tried looking for related topics but haven't come up with anything relevant. Some related answers fool around with HtmlHelper.ViewContext.HttpContext.Items[""] but I'm unsure how to use it.
What I want is something like this: string scripts = GetScriptsForView(action, controller); which returns the section used in the view like this: #section Scripts {
To clarify (edit):
I'm trying to replace the "RenderBody()" of the layout page with ajax calls, so that I don't have to load the layout containing the static header every time.
I have managed to replace all <a>-tags with ajax calls replacing the <div> containing the view, but am unable to get the javascripts working.
I could remove the #section scripts { from the cshtml-files and let the script tag get loaded with the html view. The problem with this is that if I reload the page it calls the scripts for that view before calling the scripts of the layout page, resulting in errors. Therefore I wish to load the scripts separately.
TL;DR
While you can load sections and contents in separate requests (see example 1), but you don't need to do that. Instead:
You can have different Layout pages for different purposes and dynamically decide which layout to use for the view. For example a full layout page for normal requests and a simple layout page without headers and footers for ajax requests (see example 2).
You can decide dynamically about the layout page in _ViewStart.cstml or in the controller, based on different request parameters, like Request.Headers, Request.QueryString, Request.IsAjaxRequest, etc.
Long Answer
Here are some useful notes about the layout, section, view and partial view which may help you to handle the case:
Specify Layout in return View() - When returning a View you can specify the layout for the view. For example return View("Index", masterName: "_SomeLaypout"). You can have some logic to dynamically decide about the layout name.
Specify Layout in _LayoutStart.cshtml - When returning a View, you can specify the Layout in _ViewStart.cshtml file, for example #{ Layout = "_Layout"; }. You can have some logic to dynamically decide about the layout name.
Render content without Layout - When return a view using PartialView() method, it will render the whole content of the view without any layout or without rendering any section. It's equivalent to using return View and setting Layout to null, in _ViewStart.cshtml)
Render Section without any Content - You can have a layout having just a RenderSection method. Then if you return a view using that layout, it just renders the specified section of that view and will ignore the contents.
Scripts with/without Section - Considering above options, when you put scripts in the script tag without putting in a Section, you guarantee they will be returned as part of the result, regardless of calling return View or return PartialView or having or not having Layout. So in some cases you may want to put scripts without sections. In this case, when you load the partial view using ajax call, it contains the content as well as scripts of the partial view.
In some cases you may want to have some common content/scripts even for partial views, in such cases you can use Section, also have a Layout page which renders the section and contains common things that you want to have in all partial view. In this case you need to return the partial view using return View and specify that specific layout page.
Example 1 - Return just scripts or just content in an ajax request
The following example shows how you can send an ajax request to get content and send an ajax request to get scripts section.
Please note, I don't recommend using different requests for getting
content or getting scripts separately and this example is just for
learning purpose to show you what you can do with Layout pages and
_ViewStart.
To do so, follow these steps:
Change the _ViewStart.cshtml content to:
#{
if(Request.QueryString["Layout"]=="_Body")
{
//Just content of the page, without layout or any section
Layout = null;
}
else if (Request.QueryString["Layout"] == "_Script")
{
//Just script section
Layout = "~/Views/Shared/_Script.cshtml";
}
else
{
//Everything, layout, content, section
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
Note: Instead of a Request.QueryString, you can easily rely on a Request.Header or Request.IsAjaxRequest() or ... base on your requirement.
Then just for _Script, add a new layout page named _script.cshtml having the following content:
#RenderSection("scripts", required: false)
Then:
To get the script section, send a normal ajax request and add the following query string: Layout=_Script.
To get the content without script section, send a normal ajax request and add the following query string: Layout=_Body.
To get the whole content, send a normal ajax request without specifying any Layout query string.
For example, assuming you have a Sample action in Home controller:
[HttpGet]
public ActionResult Sample()
{
return View();
}
Which returns the following Sample.cshtml view:
<div id="div1" style="border:1px solid #000000;">
some content
</div>
#section scripts {
<script>
$(function () {
alert('Hi');
});
</script>
}
In client side, to get the script section:
<button id="button1">Get Sample Content</button>
<script>
$(function () {
$('#button1').click(function () {
$.ajax({
url: '/home/sample',
data: { Layout: '_Script' },
type: 'GET',
cache: false,
success: function (data) { alert(data); },
error: function () { alert('error'); }
});
});
});
<script>
Example 2 - Return Content Without Layout Using Ajax requests
In this example, you can see how easily you can return content and scripts of the views without layout for ajax requests.
To do so, follow these steps:
Change the _ViewStart.cshtml content to:
#{
if(Request.IsAjaxRequest())
{
Layout = "~/Views/Shared/_Partial.cshtml";
}
else
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
Add a new layout page named _PartialView.cshtml having the following content:
#RenderBody()
#RenderSection("scripts", required: false)
Get the view using ajax. For example, assuming you have a Sample action in Home controller:
[HttpGet]
public ActionResult Sample()
{
return View();
}
Which returns the following Sample.cshtml view:
<div id="div1" style="border:1px solid #000000;">
some content
</div>
#section scripts {
<script>
$(function () {
alert('Hi');
});
</script>
}
Get the result using ajax:
<button id="button1">Get Sample Content</button>
<script>
$(function () {
$('#button1').click(function () {
$.ajax({
url: '/home/sample',
type: 'GET',
cache: false,
success: function (data) { alert(data); },
error: function () { alert('error'); }
});
});
});
<script>
As per my understanding I guess you are looking for load the page via Ajax without reloading the entire page.
Did you check the Kool Swap Jquery plugin? Hope this will match your requirement.

Bizzare behavior of MVC Action/RenderAction, ajax post, and Partial Views

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.

How to update part of a cshtml shared layout on intervals?

I want to modify the content of a div in my shared layout when there is an update at my database. Whats the best way to go about it ? Timers to check database + somehow update view from controller ? In view c# functions ? ajax ?(don't know much about it) or some other way ? Thanks in advance.
Use setTimeout utility of javascript to get timer behavior.
Create a Controller Action and its associated partial view which will have the content you need to load dynamically. You can return a formatted Html from the view or a structured Json object from the controller action whichever is suitable for you..
considering that your following is your DIV tag.
<div id="dynamicContent"></div>
use
$(function(){
var function updatecontent()
{
$("#dynamicContent").load(URL)
setTimeout(updatecontent,5000);
}
setTimeout(updatecontent,5000);
});
to load content dynamically, url would be
YourDomain.com/Controller/Action
$.load()
will load the content of partial view using Ajax, and you will get a nice behavior on page.

Asp.net mvc3 periodic refresh of results without reloading the page

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.

MVC: Refreshing a grid via jQuery

I have a grid (foreach in view) which is shown based on a GET request.
For the POST request, I want to return a filtered view of the grid. The grid is already a partial view, so just returning the grid is no problem.
However, I am looking for some sample code on how I get my filter conditions (there are quite a few, I would have those selected clientside via dropdowns) back to the controller's POST request.
I'd really appreciate some sample code, client & server side using jQuery as the Javascript library for the client side code.
Thank you!
I write code like this.
var url = '<%= Url.Action("List", new { controller = "ControllerName" }) %>';
$.post(url,
$("#criteria_form").serialize(),
function(data) {
$("#list_holder").html(data);
}
);
The C# part would look like this, if you use Craig's example, note that the action's arguments need to have the same name as in the html search criteria form !
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(string searchtext)
{
// retrieve data here based on searchtext
//return partial view to be used in the grid
return View("_partial", myDataCollection)
}
You can also look into jQuery addons like jqGrid or TableSorter.

Categories

Resources