loading gif in mvc - asp.net-mvc

I have a method in my controller like this
public string UpdateResource()
{
Thread.Sleep(2000);
return string.Format("Current time is {0}", DateTime.Now.ToShortTimeString());
}
I have a html button in my view page and when I click on that I want a loading gif image to appear and then disappear after 2000ms. Below is my html
<input type="button" id="btnUpdate" value="Update" />
<img id="loading" src="/Images/ajax-loader.gif" alt="Updating ..." />
<div id="result"></div>
How can I call the controller method. I have seen Html.ActionLink but I want this on button click and not a hyperlink.
Please help

First change to UpdateResource method. Now it returns ActionResult:
public ActionResult UpdateResource()
{
Thread.Sleep(5000);
return Content(string.Format("Current time is {0}", DateTime.Now.ToShortTimeString()));
}
We have to hide image when document is loaded so we change image tag to:
<img id="loading" src="../../Content/progress.gif" alt="Updating ..." style="display: none;" />
We have added style="display:none".
Then we are using jQuery:
<script type="text/javascript">
$(document).ready(
function() {
$('#btnUpdate').click(
function() {
$('#loading').show();
$.get('<%= Url.Action("UpdateResource") %>', {},
function(data) {
$('#result').html(data);
$('#loading').hide();
});
}
);
}
);
</script>
When document is loaded, we are setting click action to your button. It shows progress and then uses ajax to get ActionResult. When ActionResult comes back, we are hiding progress and setting content of #result div with returned data.

Related

DirtyForms does not work properly with $.blockUI

I'm using DirtyForms and $.blockUI plugin, the latter to change pages when clicking on links (in my app, some pages take a couple of seconds more to load and a visual feedback is fine).
When I change field content and then click any link, DirtyForms is triggered: but when I cancel the process to stay on the page, $.blockUI starts its game, resulting in a stuck page
$('form[method="post"]').dirtyForms();
$('a').on('click', function(){
$.blockUI();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js"></script>
<p>Change the field content to activate DirtyForms, then click on the link.<br>
When the popup appears, click on "cancel" to stay on the page.<br>
Watch blockUI getting fired as the link is going to be followed</p>
<form action="#" method="post">
<input type="text" name="username" required>
<button type="submit">send</button>
</form>
click me after changing field content
Please, any solution?
EDIT: I also tried with stay.dirtyforms and afterstay.dirtyforms events, but they have no effect. defer.dirtyforms seems to work but the event is triggered twice (I put a console.log() to check) and I am not sure this is the way to go...
I've edit my answer: I've added some line of code to disable first the onbeforeunload dialog alert, taken from here. And at the end a link to an answer with another idea you can try.
My idea: you have to prevent the default link action and use the $.blockUI Modal Dialogs methods to open a custom dialog, then catch the link attribute href from the link put it inside a variable and use the variable value for the #yes button of the dialog.
See if this solution can meet your needs
/* beforeunload bind and unbind taken from https://gist.github.com/woss/3c2296d9e67e9b91292d */
// call this to restore 'onbeforeunload'
var windowReloadBind = function(message) {
window.onbeforeunload = function(event) {
if (message.length === 0) {
message = '';
};
if (typeof event == 'undefined') {
event = window.event;
};
if (event) {
event.returnValue = message;
};
return message;
}
};
// call this to prevent 'onbeforeunload' dialog
var windowReloadUnBind = function() {
window.onbeforeunload = function() {
return null;
};
};
var linkToFollow; // href to follow
$('form[method="post"]').dirtyForms();
$('a').on('click', function(e){
e.preventDefault();
windowReloadUnBind(); // prevent dialog
$.blockUI({ message: $('#question'), css: { width: '275px' } });
linkToFollow = $(this).attr('href');
});
$('#no').click(function() {
$.unblockUI();
return false;
});
$('#yes').click(function() {
$(window.location).attr('href', linkToFollow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js"></script>
<p>Change the field content to activate DirtyForms, then click on the link.<br>
When the popup appears, click on "cancel" to stay on the page.<br>
Watch blockUI getting fired as the link is going to be followed</p>
<form action="#" method="post">
<input type="text" name="username" required>
<button type="submit">send</button>
</form>
click me after changing field content
<div id="question" style="display:none; cursor: default">
<h6>Would you like to contine?.</h6>
<input type="button" id="yes" value="Yes" />
<input type="button" id="no" value="No" />
</div>
Other idea taken from another answer: Other idea would be to make a simple jQuery.ajax({}) call before return value in beforeunload as seen in this answer

Ajax.ActionLink alternative with mvc core

In MVC5 there is #Ajax.ActionLink that is useful to update just a partial view instead of reloading the whole View. Apparently in MVC6 is not supported anymore.
I have tried using #Html.ActionLink like the following but it doesn't update the form, it return just the partial view:
View:
#Html.ActionLink("Update", "GetEnvironment", "Environments", new { id = Model.Id }, new
{
data_ajax = "true",
data_ajax_method = "GET",
data_ajax_mode = "replace",
data_ajax_update = "environment-container",
#class = "btn btn-danger"
})
control:
public async Task<ActionResult> GetEnvironment(int? id)
{
var environments = await _context.Environments.SingleOrDefaultAsync(m => m.Id == id);
return PartialView("_Environment",environments);
}
Partial view:
#model PowerPhysics.Models.Environments
this is a partial view
Then I tried using ViewComponents. When the page loads the component works correctly but I don't understand how to refresh just the component afterward (for example with a button):
View:
#Component.InvokeAsync("Environments", new { id = Model.Id }).Result
component:
public class EnvironmentsViewComponent : ViewComponent
{
public EnvironmentsViewComponent(PowerPhysics_DataContext context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync(int? id)
{
var environments = await _context.Environments.SingleOrDefaultAsync(m => m.Id == id);
return View(environments);
}
}
How can I update just a part of a view by using PartialViews in MVC6?
You can use a tag as follows:
<a data-ajax="true"
data-ajax-loading="#loading"
data-ajax-mode="replace"
data-ajax-update="#editBid"
href='#Url.Action("_EditBid", "Bids", new { bidId = Model.BidId, bidType = Model.BidTypeName })'
class="TopIcons">Link
</a>
Make sure you have in your _Layout.cshtml page the following script tag at the end of the body tag:
<script src="~/lib/jquery/jquery.unobtrusive-ajax/jquery.unobtrusive-ajax.js"></script>
ViewComponent's are not replacement of ajaxified links. It works more like Html.Action calls to include child actions to your pages (Ex : Loading a menu bar). This will be executed when razor executes the page for the view.
As of this writing, there is no official support for ajax action link alternative in aspnet core.
But the good thing is that, we can do the ajaxified stuff with very little jQuery/javascript code. You can do this with the existing Anchor tag helper
<a asp-action="GetEnvironment" asp-route-id="#Model.Id" asp-controller="Environments"
data-target="environment-container" id="aUpdate">Update</a>
<div id="environment-container"></div>
In the javascript code, just listen to the link click and make the call and update the DOM.
$(function(){
$("#aUpdate").click(function(e){
e.preventDefault();
var _this=$(this);
$.get(_this.attr("href"),function(res){
$('#'+_this.data("target")).html(res);
});
});
});
Since you are passing the parameter in querystring, you can use the jQuery load method as well.
$(function(){
$("#aUpdate").click(function(e){
e.preventDefault();
$('#' + $(this).data("target")).load($(this).attr("href"));
});
});
I add ajax options for Anchor TagHelper in ASP.NET MVC Core
you can see complete sample in github link :
https://github.com/NevitFeridi/AJAX-TagHelper-For-ASP.NET-Core-MVC
after using this new tagHelper you can use ajax option in anchor very easy as shown below:
<a asp-action="create" asp-controller="sitemenu" asp-area="admin"
asp-ajax="true"
asp-ajax-method="get"
asp-ajax-mode="replace"
asp-ajax-loading="ajaxloading"
asp-ajax-update="modalContent"
asp-ajax-onBegin="showModal()"
asp-ajax-onComplete=""
class="btn btn-success btn-icon-split">
<span class="icon text-white-50"><i class="fas fa-plus"></i></span>
<span class="text"> Add Menu </span>
</a>
Use tag helpers instead and make sure to include _ViewImport in your views folder.
Note: Make sure to use document.getElementsByName if there are several links pointing to different pages that will update your DIV.
Example - Razor Page
<script type="text/javascript" language="javascript">
$(function () {
var myEl = document.getElementsByName('theName');
$(myEl).click(function (e) {
e.preventDefault();
var _this = $(this);
$.get(_this.attr("href"), function (res) {
$('#' + _this.data("target")).html(res);
});
});
});
</script>
<a asp-action="Index" asp-controller="Battle" data-target="divReplacable" name="theName" >Session</a>
<a asp-action="Index" asp-controller="Peace" data-target="divReplacable" name="theName" >Session</a>
<div id="divReplacable">
Some Default Content
</div>

Second time partialview not loading to div via from .ajax() in MVC4

I have issue loading partialview to div second time. I have checked previous posts in SO but non of them really helped me. So I am posting my issue here.
index.cshtml
<div id="DivEmailContainer" style="display:block" class="row">
</div>
_EditEmail.cshtml
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-2 ">
<input type="submit" value="Save" class="btn btn-success width100per" />
</div>
script type="text/javascript">
$(function () {
$("#frmEmail").validate({
rules: {
...
submitHandler: function (form) {
$.ajax({
url: 'PostEditEmail',
type: 'Post',
data: $(form).serialize(),
success: function (result) {
alert("In success");
$('#DivEmailContainer').html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
},
complete: function (xhr, textStatus) {
alert(xhr.responseText);
alert(textStatus);
}
});
}
});
controller
public PartialViewResult PostEditEmail(string actiontype, FormCollection col)
{
var communicationLocation = string.Empty;
....
return PartialView("_EditEmail", memberemail);
}
First time partialview loading into DivEmailContainer to error. If submit again partialview loading full post back. not even it is calling submitHandler.
Only thing I observed is 1st time submit <form post was /ContactInformation/GetEditEmailbut when I submit second time <form post was /ContactInformation/PostEditEmail.
What could be wrong?
update
second time Forloop scriptblock loading. May be it is issue with Forloop?
#using (Html.BeginScriptContext())
{
Html.AddScriptBlock(
update
issue with forloop htmlhelper, not with ajax. secondtime script is not loading. #Russ Cam can help on this.
from my experience putting script in a partial leads to very inconsistent results. expecially with the script being inserted into the middle of the page. I would highly recommend that you pull your script from the partial and put it on the main page. Since the partial is loaded after the page load you will need to tie the script to the partial one of 2 ways.
1. tie the events to the document
$(document).on('click', '.targetClass', function(){
//do stuff
});
for example to put an id on your input and change it to a button
<input type="button" value="Save" id="btnSave" class="btn btn-success width100per" />
your click event would then be
$(document).on('click', '#btnSave', function(){
//your ajax call here
});
being tied to the document this click event would fire even though the input is inserted into the document after load
put the script in a function that is called after the partial is loaded
change your
$(function () {
to
function partialScript(){
and call this function after the partial is loaded
$('#DivEmailContainer').html(result);
partialScript();
Try to load partial view like this
$("#DivEmailContainer").load('#Url.Action('ActionName', 'ControllerName')', function () {
//Perform some operation if you want after load.
});

How do I get my success message to show after ajax submitting form in Jquery ui-tab

I have form on a jQuery ui-tab, which loads data onto a list displayed on the same ui-tab. I have managed to get the data loaded, and the display to return to same tab for a further item to be entered. However depending on the sort order of the list the new item is not always visually obvious, I want to fade in a message, but I can't get it to work along with returning to the same tab without a manual page refresh.
I have attached both the scripts I am trying to use.
Script A
<script> // this one loads data perfectly but no success message appears
$(document).ready(function() {
$("#addtodoitem").live( 'submit' , function(evt) {
evt.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
$('.ui-tabs-panel:visible').html(data);
$('.itemadded').fadeIn(1000).delay(4000).fadeOut(1000);
};
});
});
});
Script B
<script> //this one shows the message and loads the data, but it also loads another
//copy of ui-tabs overlapping the original
$(document).ready(function() {
$('#addtodoitem').ajaxForm(function(data) {
$('.ui-tabs-panel:visible').html(data);
$(".itemadded").fadeIn(1000).delay(4000).fadeOut(1000);
}); return false;
});
HTML
<div id="tabs_5" class="tabs">
<h2 id="todo5" class="tablecaption">Add To-do</h2>
<p>To raise a new issue please enter the description of the issue below.</p>
<form id="addtodoitem" class="todo" method="post" action="todo_do.php?do=<?=$todo_do != '' ? "edit&to_id={$_GET['to_id']}" : 'add'?>&pub=1&site_ref=NA">
<input type="hidden" value="0" name="status" id="status">
<textarea name="todo" id="todo" placeholder="To raise a new issue, please type the details of the issue here"><?=$todo_free_text?></textarea> <br />
<input type="submit" value="Submit" class="button" />
</form>
<h2 class="tablecaption itemadded">Thank you, your item has been added to the list.</h2>
I got to a satisfactory solution by using a separate refresh link button and php page to cause the refresh after posting so the script is so:
<script type="text/javascript">
$(document).ready(function(){
$('#addtodo').click(function(e){
e.preventDefault();
if($('#todo').val()!="")
{
$.ajax({
type: 'POST',
url: 'todo_do.php',
data: { 'status': $('#status').val(),
'todo': $('#todo').val()
},
success: function(data){
$('.itemadded').slideDown(500).delay(2000).fadeOut(500);
$('.refreshtodo').slideDown(500);
$('#addtodoitem')[0].reset();
$('#tabs > ul').tabs({selected: 5 });
}
});
}
else{$('.nothing').slideDown(500).delay(1000).fadeOut(500)}
});
});
and the extra php page just contains
<?
header("Location: resident.php#tabs_5");
?>

Call Action From view

This is my action :
[HttpPost]
public ActionResult AddDispo(string idv, string dd, string df)
{
try
{
Models.indisponible model = new Models.indisponible();
model.Dd = Convert.ToDateTime(dd);
model.Df = Convert.ToDateTime(df);
model.idv = idv;
entity.indisponible.AddObject(model);
entity.SaveChanges();
TempData["Resultat"] = "La nouvelle date a été ajouté courrectement";
return RedirectToAction("Dispo", "Agence", new { idv = idv});
}
catch (Exception)
{
TempData["Resultat"] = "Une erreur se produiset Vielliez ressaiyer";
return RedirectToAction("Dispo", "Agence", new { idv = idv});
}
}
I want to call this action without using Html.beginForm from my view, i have made this trial but it hasn't worked :
<%: Html.Action("Accepter", "Adddispo", new { id = Model.idv, dd = Model.Dd, df = Model.Df })%>
Your Action method is of type HTTPOST. So you need a form posting for that action to get invoked. If you do not wish to use the form tag in your view, you may use jQuery to do a POST.
The below example does a post when user clicks on a button woth ID btnPost.
HTML ( Content of Your View)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
Name : <input type="text" id="txtName" /> <br/>
Age: <input type="text" id="txtAge" /> <br/>
Place : <input type="text" id="txtPlace" /> <br/>
<input type="button" value="Save" id="btnPost" />
<script type="text/javascript">
$(function(){
$("#btnPost").click(function(e){
e.preventDefault(); // preventing the default button submit behaviour
var name=$("#txtName").val(); //reading the text box values
var age=$("#txtAge").val();
var place=$("#txtPlace").val();
$.post("YourController/AddDispo", { idv :name, dd : age, df=place} ,function(data) {
//Do whatever with the the response. may be an alert
alert(data);
});
});
});
</script>
What it does
1) In the head section of the document, we included the reference to the jQuery library. I am including a reference from the google CDN. You may change that to include your local copy. If you are working with ASP.NET MVC, the default project template has this under the Scripts folder(version number may be different).
2) In the document ready event ($(function(){..) we are binding some functionality to the button which has an ID btnPost. We are binding the functionality on the click event. So whenever user clicks on that button, that piece of code will be executed.
3) We are reading the text box values, and making use of the post method of jQuery. It will post the data we are passing ( we are passing the values of text boxes here) to the action method. once the action method returns something back to the calle, it will be stored in the data variable. you can do further things (show some message to user/ reload some content) after checking the value of that.
Action link will always send a "GET" request. Either remove that [HttpPost] attribute from your controller action, or use a similar technique suggested by shyju. Action link has some issues with windows events, so you should stick to stylized buttons unless there is specific need for anchors. A sample styling will be :
#mybutton input[type=submit] {
background: none;
padding: 0px;
font-family: arial;
font-size: 1em;
cursor: pointer; // to make it look like link
border: none; // --- " -----
}

Resources