Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Monday, July 14, 2014

ASP.net MVC ActionLink with Image: Part 3 (Ajax)

In my previous posts we've seen how to implement some custom helpers to add  Bootstap Glyphs or Images to ActionLinks.

Now we're going to see how to do the same thing but with Ajax support too.

The basic things to do is to build the html code taking care of all the "ajax-related stuff" that the normal Ajax.ActionLink helper adds.

In this example I used the glyph as image, but you can use the same approach also with the normal images.

/// <summary>
/// Create an Ajax.ActionLink with an associated glyphicon
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="linkText"></param>
/// <param name="actionName"></param>
/// <param name="controllerName"></param>
/// <param name="glyphicon"></param>
/// <param name="routeValues"></param>
/// <param name="htmlAttributes"></param>
/// <returns></returns>
public static MvcHtmlString ImageActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, string glyphicon, AjaxOptions ajaxOptions, RouteValueDictionary routeValues = null, object htmlAttributes = null)
{
 //Example of result:           
 //<a id="btnShow" href="/Customers/ShowArtworks?customerId=1" data-ajax-update="#pnlArtworks" data-ajax-success="jsSuccess" 
 //data-ajax-mode="replace" data-ajax-method="POST" data-ajax-failure="jsFailure" data-ajax-confirm="confirm" data-ajax-complete="jsComplete" 
 //data-ajax-begin="jsBegin" data-ajax="true">
 //  <i class="glyphicon glyphicon-pencil"></i>
 //  <span>Edit</span>
 //</a>

 var builderI = new TagBuilder("i");
 builderI.MergeAttribute("class", "glyphicon " + glyphicon);
 string iTag = builderI.ToString(TagRenderMode.Normal);

 string spanTag = "";
 if (!string.IsNullOrEmpty(linkText))
 {
  var builderSPAN = new TagBuilder("span");
  builderSPAN.InnerHtml = " " + linkText;
  spanTag = builderSPAN.ToString(TagRenderMode.Normal);
 }

 //Create the "a" tag that wraps
 var builderA = new TagBuilder("a");

 var requestContext = HttpContext.Current.Request.RequestContext;
 var uh = new UrlHelper(requestContext);

 builderA.MergeAttribute("href", uh.Action(actionName, controllerName, routeValues));

 //Ajax section
 builderA.MergeAttribute("data-ajax", "true");
 builderA.MergeAttribute("data-ajax-update", ajaxOptions.UpdateTargetId.StartsWith("#") ? ajaxOptions.UpdateTargetId : "#" + ajaxOptions.UpdateTargetId);
   
 if (!string.IsNullOrEmpty(ajaxOptions.InsertionMode.ToString()))
  builderA.MergeAttribute("data-ajax-mode", ajaxOptions.InsertionMode.ToString());            
 
 if (!string.IsNullOrEmpty(ajaxOptions.OnBegin))
  builderA.MergeAttribute("data-ajax-begin", ajaxOptions.OnBegin);
 
 if (!string.IsNullOrEmpty(ajaxOptions.OnComplete))
  builderA.MergeAttribute("data-ajax-complete", ajaxOptions.OnComplete);
   
 if (!string.IsNullOrEmpty(ajaxOptions.OnFailure))
  builderA.MergeAttribute("data-ajax-failure", ajaxOptions.OnFailure);
   
 if (!string.IsNullOrEmpty(ajaxOptions.OnSuccess))
  builderA.MergeAttribute("data-ajax-success", ajaxOptions.OnSuccess);
   
 if (!string.IsNullOrEmpty(ajaxOptions.Confirm))
  builderA.MergeAttribute("data-ajax-confirm", ajaxOptions.Confirm);
  
 if (!string.IsNullOrEmpty(ajaxOptions.HttpMethod))
  builderA.MergeAttribute("data-ajax-method", ajaxOptions.HttpMethod);

 if (htmlAttributes != null)
 {
  IDictionary<string, object> attributes = new RouteValueDictionary(htmlAttributes);
  builderA.MergeAttributes(attributes);
 }

 builderA.InnerHtml = iTag + spanTag;

 return new MvcHtmlString(builderA.ToString(TagRenderMode.Normal));
}


As you can see, the code is similar to the one we've seen in the other posts but with the exception of the fact we are extending an "AjaxHelper" insetead of  an "HtmlHelper" and the add of the "ajax section"

Tuesday, May 14, 2013

Free technical e-book on the Microsoft platform


While a lot of information on application development is available on the internet and in books, that information is becoming harder to digest. If you do not enjoy reading several 500+ page books, or scouring the web for relevant blog posts and articles, you have come to the right place.
Syncfusion publishes the Succinctly series concise technical books that target developers working on the Microsoft platform. Each book is around 100 pages and is guaranteed to enlighten you on the topic of interest. Download a copy, get a cup of your favorite beverage, and enjoy!

Tuesday, October 4, 2011

jQuery modal alert in Page_Load


To insert a jQuery alert into Page_Load method of an our WebForm (maybe for a bad result of an operation) could not be simple, 'cause Page_Load method is invoked before thar the page loads included script files.

To solve it, just do this:


Protected Sub Page_Load(sender As Object, e As System.EventArgsHandles Me.Load

[…]
ScriptManager.RegisterClientScriptInclude(Page, Page.GetType, Guid.NewGuid().ToString(), Page.ResolveUrl("~/js/jquery-1.6.2.min.js"))
        ScriptManager.RegisterClientScriptInclude(Page, Page.GetType, Guid.NewGuid().ToString(), Page.ResolveUrl("~/js/jquery-ui-1.8.16.custom.min.js"))
        Dim sb As New StringBuilder
        sb.Append("$(function() { ")
        sb.Append(" $( '#dialog-message-error' ).dialog({")
        sb.Append("    modal: true,")
        sb.Append("    buttons: {")
        sb.Append("        Ok: function() {")
        sb.Append("               $( this ).dialog( 'close' );")
        sb.Append("        }")
        sb.Append("    }")
        sb.Append(" });")
        sb.Append("});")
        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType, Guid.NewGuid().ToString(), sb.ToString, True)
End Sub


It's supposed to have jquery and jquery-ui script files into the "js" folder on application root, and that this div exists:


<div id="dialog-message-error" title="Error" style="display: none; font-size: small">
<div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
<p>
<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;">span>
<strong>Error:strong> Error text....
p>
div>
div>

Tuesday, September 20, 2011

UpdateProgress dinamically centered



<script language="JavaScript" type="text/javascript">
        function adjustDivs() {           
            internal= document.getElementById('divCalculateInt');
            external= document.getElementById('divCalculate');
            dfs = interno.style;
           
            dfs.left = (external.innerWidth - internal.offsetWidth) / 2;
        }

        window.onload = adjustDivs;
        window.onresize = adjustDivs;
        window.onscroll = adjustDivs;
<script>

<asp:UpdatePanel ID="updXXX" runat="server">
<ContentTemplate>
       […]
<ContentTemplate>
<asp:UpdatePanel>

<asp:UpdateProgress ID="updprogXXX" runat="server" AssociatedUpdatePanelID="updXXX" DisplayAfter="150">
<ProgressTemplate>
             <div id="divCalculate" align="center" style="top: 200px; position: absolute; top:0; bottom:0; right:0; left:0;background-color:rgba(0,0,0,0.5)">
                    <div id="divCalculateInt" align="center" style="border: solid 1px #000000; background: #FFFFFF;padding: 5px; width: 320px; height: 50px;margin-top:300px">
                        <asp:Label runat="server" ID="lblLoading2" Text="Computing in progress..."><asp:Label>
                        <asp:Image ID="imgLoading" runat="server" ImageAlign="left" SkinID="imgLoadingBar" /><br /><br />
                        <asp:Label runat="server" ID="lblLoadingInfo" Text="This operation may last some minutes" Font-Size="X-Small" >asp:Label>
                    <div>
                <div>               
        <ProgressTemplate>
<asp:UpdateProgress>

Wednesday, June 3, 2009

Disable a button after click (Asp.Net)

To disable a button after click, to avoid that a user re-click on it before the completion of the operation, we have tu use javascript.
The problem is that the disable javascript function remove the postback ability of the button.

To bypass this problem, we can use the following code, writing it into Page Load event:

Me.btn.Attributes("onclick") = "this.disabled = true; " & Page.GetPostBackEventReference(btnSub).ToString

Into this code, btn is the id of the button and btnSub is the routine that normally handles btn.Click event

Saturday, May 9, 2009

jQuery Intellisense in Visual Studio 2008 (VS 2008)

To enable intellisense completion for jQuery within VS you'll want to follow three steps:


Step 1: Install VS 2008 SP1

VS 2008 SP1 adds richer JavaScript intellisense support to Visual Studio, and adds code completion support for a broad range of JavaScript libraries.

You can download VS 2008 SP1 here.


Step 2: Install VS 2008 Patch KB958502 to Support "-vsdoc.js" Intellisense Files

Few weeks ago Microsoft shipped a patch that you can apply to VS 2008 SP1 that causes Visual Studio to check for the presence of an optional "-vsdoc.js" file when a JavaScript library is referenced, and if present to use this to drive the JavaScript intellisense engine.

These annotated "-vsdoc.js" files can include XML comments that provide help documentation for JavaScript methods, as well as additional code intellisense hints for dynamic JavaScript signatures that cannot automatically be inferred. You can download it here.


Step 3: Download the jQuery-vsdoc.js file

Microsoft worked with the jQuery team to put together a jQuery-vsdoc.js file that provides help comments and support for JavaScript intellisense on chained jQuery selector methods. You can download both jQuery and the jQuery-vsdoc file from the official download page on the jQuery.com site.

Save the jquery-vsdoc.js file next to your jquery.js file in your project (and make sure its naming prefix matches the jquery file name). For example, if the jQuery library file is jquery.1.2.6.js, the vsdoc file will be named jquery-.1.2.6-vsdoc.js


You can then reference the standard jquery file with an html <script/> element like so:

<script src="../Folder/jquery.1.2.6.js" type="text/javascript"></script>

When you do this VS will now look for a -vsdoc.js file in the same directory as the script file you are referencing, and if found will use it for help and intellisense.

Friday, December 12, 2008

Response.Redirect in UpdatePanel Ajax

Sometimes we have to use the Response.Redirect function in a UpdatePanel... But in most cases this function give an error. Usually, it's 'cause a bit of configuration is missing, in web.config
So, if we add

<httpModules>

<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

</httpModules>


all works fine.

Wednesday, June 4, 2008

Ajax - Response.Write with UpdatePanel

Usually, the Response.Write() method inside an UpdatePanel doesn't work.
To solve this problem, a workaround is to insert a LinkButton out of the UpdatePanel and to associate this control with the postback generated from the object inside the panel.


HTML
<asp:UpdatePanel ID="upd" runat="server">
    …
    <asp:Button runat="server" ID="BUTTON" Text="Click" />
    …
    </asp:UpdatePanel>
<asp:LinkButton ID="ALinkButton" runat="server"></asp:LinkButton>



CODE
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    …
    AddHandler Me.ALinkButton.Click, AddressOf FUNCTION
    Me.BUTTON.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(Me.ALinkButton, ""))

    If Not Page.IsPostBack Then
        …
    End If
    …
End Sub

Protected Sub FUNCTION(ByVal sender As Object, ByVal e As System.EventArgs)
    …
    Response.Write("Text")
    …
End Sub

Friday, May 16, 2008

Ajax - FadeIn and FadeOut Animation

With Microsoft AjaxToolkit you can do a lot oh things but the most complex (for me) is to apply an animation to an object. However, with a small amount of lines, you can create simple animations and effects for a WebForm.

In this example, we wanna show a customized tooltip when the mouse is over a button and then that it disappears when the mouse is out. We use fadeIn and fadeOut animations, 0.5 seconds long and with a framerate of 20fps:


<cc1:AnimationExtender ID="AnimationExtender1" runat="server"
TargetControlID="ImageButton1">
     <Animations>
          <OnMouseOver>
               <sequence>
                    <StyleAction AnimationTarget="info"
                    Attribute="display" Value="block"/>
                    <FadeIn AnimationTarget="info" Duration=".5"
                    Fps="20" />
               </sequence>
          </OnMouseOver>
          <OnMouseOut>
               <sequence>
                    <FadeOut AnimationTarget="info" Duration=".5"
                    Fps="20" />
                    <StyleAction AnimationTarget="info"
                    Attribute="display" Value="none"/>
               </sequence>
          </OnMouseOut>
     </Animations>
</cc1:AnimationExtender>



info is a "div" that contains our tooltip. Must be written in this way:

<div id="info" style="display: none; z-index: 2; opacity: 0;">