Display busy indicator while controller action work - c#

I have a problem right now and I hope you can help me.
My problem is that I have a Controller in which I generate a file as byteArray (without saving it on hard disk), which I return to download.
These action takes up to 5-6 seconds until its generated. Now I would like to display a busy indicator for the user, but I don't know, how can I identify, when my controller is done!?
Here is my code:
This is the code to call my Controller action in my "View.cshtml":
<span class="fa fa-bar-chart"></span>
This my Controller code:
public ActionResult DownloadAnalysis()
{
var response = StartAnalysis();
if (response.AnalysisByteArray != null && response.AnalysisByteArray.Length > 0)
{
var cd = new System.Net.Mime.ContentDisposition
{
FileName = response.FileName,
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(response.AnalysisByteArray , "text/csv");
}
return null;
}
I thank you in advance for your help!
Best Regards

Instead of the anchor tag use a button and onclick event to call the controller.
your html should be like
<button title="Get analysis file" onclick="getFile()"><span class="fa fa-bar-chart"></span></button>
and in JavaScript use window.location to call the controller action
<script>
function getFile(){
//here you can add script to change cursor to progress of add some html element to show loading.
window.location.href = '/Analysis/DownloadAnalysis/';
}
</script>

Related

Call function from cshtml to cshtml.cs using Models

I am new to asp.net core and Razor, i am trying to call a function from cshtml page to his inner cs page:
<button onclick="#{Model.GetUserInfo(1);};" type="submit">Search</button>
cshtsml.cs
public UserInfo GetUserInfo(int userId)
{
using (var client = new HttpClient())
{
var response = client.GetAsync($"localhost:44322/api/User/user/{userId}{userId}");
var body = response.Result.Content.ReadAsAsync<UserInfo>().Result;
return body;
}
}
I would like to get the information back from the api and display the information that i received.
With this code if i put { } around the Model.GetUserInfo(1); it doesn't display the button, without the { } it just doesn't compile.
Any of you can help me with it? thanks.
Step 1 - You can write a javascript function which will send an ajax request to your controller method
Step 2 - Return the data you want from this method
Assuming your controller name is Home, you can do something like this-
<button onclick="GetData()" type="submit">Search</button>
function GetData() {
$.get("/Home/GetUserInfo", function (data) {
// Here put what do you want from received data
});
}

Show ViewBag message for some seconds then redirect to another action

I have an Action Method that sets a message to ViewBag and returns to the HomePage, like,
ViewBag.errormsg = "Some Temporary message";
return RedirectToAction("Index", "Dashboard");
As per this approach User won't be able to see the ViewBag.errormsg in that page, Because it redirects to Dashboard immediately, But I want to show That message for 1 to 2 second then after redirect to dashboard.
I have tried using Task.WaitAll(); method to delay the call for RedirectToAction like here,
ViewBag.errormsg = "Some Temporary message";
Task.WaitAll(Task.Delay(2000));
return RedirectToAction("Index", "Dashboard");
But it's fairly a silly work, that ViewBag won't show message until the return method is called, Is there any simple way to accomplish this ?
I think TempData is not suitable in my case because I don't want to show that ViewBag Message to HomePage, It should be shown in the current page.
You wont be able to do that on the server side, you'll have to use javascript.
You can use:
window.setTimeout(function(){
window.location.href='your URL';
}, 2000);
I figured out what process that you want to do:
Controller => Current view => Redirect => Dashboard view
First, include your message in current view:
ViewBag.errormsg = "Some Temporary message";
return View("CurrentView");
Set an HTML element to show that message and use JS timeout on current CSHTML view:
<script type="text/javascript">
function onMessageShow() {
var msg = "#ViewBag.errormsg";
// if the message exists, set redirection to dashboard page
if (msg != null || typeof msg !== "undefined") {
setTimeout('redirect', 5000); // 5 seconds for example
}
}
function redirect() {
window.location.href = "#Url.Content("Index", "Dashboard")";
// or use window.location.replace, depending what your need
}
</script>
<html>
<body onload="onMessageShow()">
<!-- simplified for brevity -->
<p>#ViewBag.errormsg</p>
<!-- simplified for brevity -->
</body>
</html>
Task.WaitAll with Task.Delay used together in server-side to delay execution of server-side process (including async processes), in your case there are client-side events which redirecting to index page after message appears.
CMIIW.

Ajax call gets cached, despite the appropriate parameter

I'm currently writing a MVC C# application. Everything works just fine. I have a bit of functionality, where I fill up a Bootstrap modal box using an Ajax call, but the new page gets cached, despite my efforts to prevent that.
On my main page I have the following actionhandler to fill up the modal box:
function setExtraPermsOrAtts(appID){
$.ajax({
cache:false,
url: "/Group/_modifyAppPermissionsOfGroup?appID=" + appID
}).done(function (result) {
$("#addApplicationBody").html(result);
$('#modal-add-application').modal('show');
});
}
This gets caught by the following method:
public ActionResult _modifyAppPermissionsOfGroup(int? appID = 0)
{
if (appID != 0)
{
ViewBag.selectedAppID = appID;
Session["selectedGroupAppID"] = appID;
ViewBag.modifyPermsLater = true;
}
Group group = (Group)Session["currentGroup"];
return View(group);
}
Another thing that might be relevant is the point where it 'goes wrong'. The resulting View in the Modalbox, has a few radio buttons, depending on the content of the database. There I do a razor statement to get the DB value:
bool valueOfRadButtons = BusinessLogic.Domain.GroupIS.getExistingGroupPermission(
Model.LoginGroupID, myItem.ApplicationPermissionID).LoginPermissionState;
Does anyone know where I'm going wrong? Is it the Ajax call? The ActionResult method in the Controller? Or the inline razor statement? I know the data gets saved properly, cause I see so in the DB
You can specify that the response shouldn't be cached like this:
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
It can be more easy if you make your own attribute and decorate the action with it as shown here.

Call c# method from javascript for a redirect

I have a c# method for a redirect
[UIAuthentication()]
[UIMethod("cancelredirect", "mth"), UIMethodGroup("employeradmin")]
public void CancelRedirect(RequestContext Context)
{
Context.Redirect(string.Format("View.mth?EmployerID={0}", _employerID));
}
From this I have made a javascript function which is called if the cancel button on a form is pressed.
function getCancel() {
var confirmCancel = confirm('Are you sure you want to cancel?');
if(confirmCancel)
{
//redirect here
}
else
{
return false;
}
};
<input type="submit" id="Cancel" value="Cancel" name="Cancel" class="input_button" onclick="return getCancel();"/>
I was just wondering how would you call the c# method from the javascript to redirect to the page view.mth? I am not 100% sure how to do this as I have never done one one these before. Thanks for any help which you can give
Actually your question should be: "How to call action method from java-script?"
Assuming your controller class name: EmployeeController
if(confirmCancel)
{
document.location = = '/Employee/CancelRedirect';
}
Please go through following link for more info: How to redirect to another webpage in JavaScript/jQuery?
when you call server method by ajax, you can't do Redirect ,because the response handler is not the page.
If the purpose you call CancelRedirect just only to get one variable , the EmployerID from server side.
you can get EmployerID by Ajax and when the front side get the EmployerID , just redirect by :
window.location = "/View.mth?EmployerID=xxxx";
Ps: maybe you should make the ajax async property to false
try with ajax :
if(confirmCancel)
{
var url = '/Employee/CancelRedirect';
$.ajax({
url: url,
type: 'POST',
cache: false,
data :{ valeur : if you want to send a value }
})
}

How to show alert message in mvc 4 controller?

I tried show a alert box in mvc controller by if-else condition.But alert box does not display.Where is my mistake ?
Controller
public ActionResult Index()
{
int userId = Convert.ToInt32(Session["userId"].ToString());
if (WebMatrix.WebData.WebSecurity.IsAuthenticated)
{
if (userId == 90043)
{
return View();
}
else
{
TempData["Message"] = "You are not authorized.";
return RedirectToAction("Index", "Home");
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
TempData["msg"] = "<script>alert('Change succesfully');</script>";
#Html.Raw(TempData["msg"])
Use this:
return JavaScript(alert("Hello this is an alert"));
or:
return Content("<script language='javascript' type='text/javascript'>alert('Thanks for Feedback!');</script>");
You cannot show an alert from a controller. There is one way communication from the client to the server.The server can therefore not tell the client to do anything. The client requests and the server gives a response.
You therefore need to use javascript when the response returns to show a messagebox of some sort.
OR
using jquery on the button that calls the controller action
<script>
$(document).ready(function(){
$("#submitButton").on("click",function()
{
alert('Your Message');
});
});
<script>
It is not possible to display alerts from the controller. Because MVC views and controllers are entirely separated from each other. You can only display information in the view only. So it is required to pass the information to be displayed from controller to view by using either ViewBag, ViewData or TempData. If you are trying to display the content stored in TempData["Message"], It is possible to perform in the view page by adding few javascript lines.
<script>
alert(#TempData["Message"]);
</script>
<a href="#Url.Action("DeleteBlog")" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">
Response.Write(#"<script language='javascript'>alert('Message:
\n" + "Hi!" + " .');</script>");
I know this is not typical alert box, but I hope it may help someone.
There is this expansion that enables you to show notifications inside HTML page using bootstrap.
It is very easy to implement and it works fine. Here is a github page for the project including some demo images.
In Controller
TempData["err"] = "Something happenend";
In your view
var error = '#TempData["err"]';
if(error){
alert(error);
}

Categories