Archive

Archive for the ‘ASP.NET MVC’ Category

History of ECMAScript and JavaScript

September 28, 2015 Leave a comment

Hello folks ,

Nowadays “JavaScript” is used anywhere , instead of being only the client side , cross browser scripting language it has been evolved as a backend language as well (Node.js) and soon its going to handle the hardware as well http://www.espruino.com/ .

Though we use JavaScript every now and then , directly , indirectly (with Jquery) now it is part of every web developers work life , but very few know the history of JavaScript , how it has been evolving , who specifies the standards for JavaScript which made it multi browser compatible.

Lets go back in the 90s to know this

JavaScript is invented by Brendan Eich in ten days in 1995 while working with NetScape  (Now Mozilla) , It was initially named Mocha, later LiveScript, and finally JavaScript.

The change of name from LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. The final choice of name caused confusion, giving the impression that the language was a spin-off of the Java programming language, and the choice has been characterized as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web programming language.

Soon later in 1996 , Microsoft introduced VBScript and JScript in the market , But the different standards between NetScape’s Javascript and Microsoft’s JScript
made it difficult for the developers to make the website compatible in both the browsers.

Declaration of ECMA script :

In November 1996, Netscape announced that it had submitted JavaScript to ECMA International for consideration as an industry standard, and subsequent work resulted in the standardized version named ECMAScript.

In June 1997, ECMA International published the first edition of the ECMA-262 specification.

In June 1998, some modifications were made to adapt it to the ISO/IEC-16262 standard, and the second edition was released. The third edition of ECMA-262 was published on December 1999.

Development of the fourth edition of the ECMAScript standard was never completed.The fifth edition was released in December 2009. The current edition of the ECMAScript standard is 6, released in June 2015.
All Browsers javascript compilers (called ECMAScript engines) follow the ECMA script as the standard which made javascript compatible with most of the browsers those follow ECMAScript.

The evolution we have been seeing in the javascript is done by ECMA script with 6 releases till date.

List of ECMA Script features browser supporting http://kangax.github.io/compat-table/es5/

Regards ,

Ganesh Divekar

ASP.NET WEB API – What and Why

Hi Friends,

Microsoft has introduced a helpful framework with ASP.NET MVC4 called WEB API for building the http based services.

In this article we will cover following points about this new framework

1) WHAT
2) WHY  WEB API

WHAT

ASP.net Web API is an api which helps in creating the http based client and server endpoints on top of the ASP.net framework.

The Client side http based programming model has been built in to the System.net and the server side http based programming model has been built in to the WCF.

The First version of WCF did not support the Http based services.
It strongly supported the traditional Soap based service endpoints which really lack in the many other features in http like caching , compression etc.

With the release of the .NET Framework 3.5 in November 2007, Microsoft released the feature to create the simple http based endpoints but it was again more embedded in the WCF.

So Microsoft WCF team has decided to come up with the framework which is completely used for the http based services ,
As ASP.NET team is more engage in the web / http  work , routing , html Microsoft has decided to merge this framework with the ASP.Net
and introduced WEB API with the ASP.NET MVC 4 release.

WHY

If we are implementing an application whether html 5 or mobile , they need services for accessing data or to artifact the system.
In the modern programming land scape services should be created by keeping wide range of clients in mind.

Most of the applications are accessing data as JSON using HTTP based services which is going to be a trend than accessing data from traditional Soap services.

 

This article is the summary of the video by Jon Flander on the pluralsight website.

please refer http://www.asp.net/web-api for details of web api.

 

Thanks

Ganesh Divekar

ASP.NET # MVC # 21 Telerik Grid with checkboxes problem – Grid does not maintain the state of the checkboxes on changing page index

Telerik provides the best UI controls for the ASP.NET MVC application development.
Especially the Telerik Grid is used often in the web development.

However Checkbox column functionality of Telerik Grid does not maintain the state of the checkboxes on the page index changing event.
If user selects check boxes on the first page and then goes to the other and the checks made on the first page disappears.

Solution for above problem is explained with the help of following example by using the jQuery live event and the JavaScript arrays:

In this example we have a grid with checkboxes that is bound to the Model class name Order.

The order class has three properties OrderId,OrderName and IsChecked.                  IsChecked property is a Boolean  flag to see whether order is previously checked or not.

Controller code contains _ChckBoxesAjax method with a GridAction attribute that returns the IEnumerable list of type Order class.

Code on Controller
  1. [GridAction]
  2.       public ActionResult _CheckBoxesAjax()
  3.       {
  4.           List<Order> lstOrder = new List<Order>();
  5.  
  6.           lstOrder.Add(new Order { OrderId = 1, OrderName = "Order 1", IsChecked = false });
  7.           lstOrder.Add(new Order { OrderId = 2, OrderName = "Order 1", IsChecked = false });
  8.           lstOrder.Add(new Order { OrderId = 3, OrderName = "Order 2", IsChecked = true });
  9.           lstOrder.Add(new Order { OrderId = 4, OrderName = "Order 3", IsChecked = false });
  10.           lstOrder.Add(new Order { OrderId = 5, OrderName = "Order 4", IsChecked = false });
  11.           lstOrder.Add(new Order { OrderId = 6, OrderName = "Order 5", IsChecked = false });
  12.           lstOrder.Add(new Order { OrderId = 7, OrderName = "Order 6", IsChecked = true });
  13.           lstOrder.Add(new Order { OrderId = 8, OrderName = "Order 7", IsChecked = false });
  14.           lstOrder.Add(new Order { OrderId = 9, OrderName = "Order 8", IsChecked = false });
  15.           lstOrder.Add(new Order { OrderId = 10, OrderName = "Order 9", IsChecked = false });
  16.           lstOrder.Add(new Order { OrderId = 11, OrderName = "Order 10", IsChecked = true });
  17.           lstOrder.Add(new Order { OrderId = 12, OrderName = "Order 11", IsChecked = false });            
  18.           return View(new GridModel(lstOrder.AsEnumerable()));
  19.       }
  20.  
  21.   }
  22.  
  23.   public class Order
  24.   {
  25.       public int OrderId { get; set; }
  26.       public string OrderName { get; set; }
  27.       public bool IsChecked { get; set; }
  28.  
  29.   }

 

The client side code is written in the View file.There are two JavaScript function

1. RegisterLiveEventForCheckBoxes – This method should be called on the document.ready    method of the page which has the Grid on it.

2.OnCheckBoxGridDataBound – This method will be called on the OnDataBound event of the grid.

View and Client side code
  1. @{
  2.     ViewBag.Title = "_CheckBoxesAjax";
  3.     Layout = "~/Views/Shared/_Layout.cshtml";
  4. }
  5. <script type="text/javascript">
  6.  
  7.     var selectedIds;
  8.     var deselectedIds;
  9.     $(document).ready(function () {
  10.         RegisterLiveEventForCheckBoxes();
  11.  
  12.     });
  13.     function RegisterLiveEventForCheckBoxes() {    
  14.         selectedIds = []; deselectedIds = [];
  15.         $('#OrderId:checkbox').die();
  16.         $('#OrderId:checkbox').live('click', function (e) {
  17.             var $check = $(this);
  18.             if ($check.is(':checked')) {
  19.  
  20.                 if ($.inArray($(this).val(), deselectedIds) > -1) {
  21.                     deselectedIds = jQuery.grep(deselectedIds, function (value) {
  22.                         return value != $check.val();
  23.                     });
  24.                 }
  25.                 selectedIds.push($check.val());
  26.             }
  27.             else {
  28.  
  29.                 if ($.inArray($(this).val(), selectedIds) > -1) {
  30.                     selectedIds = jQuery.grep(selectedIds, function (value) {
  31.                         return value != $check.val();
  32.                     });
  33.                 }
  34.  
  35.                 deselectedIds.push($check.val());
  36.             }
  37.         });
  38.     }
  39.  
  40.     function OnCheckBoxGridDataBound(e) {
  41.         
  42.         $('input:checkbox[id*=OrderId]:checked').each(function () {
  43.             if ($.inArray($(this).val(), selectedIds) < 0) {
  44.                 selectedIds.push($(this).val());
  45.             }
  46.         });
  47.         selectedIds = jQuery.grep(selectedIds, function (item) {
  48.             return jQuery.inArray(item, deselectedIds) < 0;
  49.         });
  50.         var gridID = ($(e.target.id).selector);
  51.         $('#' + gridID + ' :checkbox').each(function () {
  52.  
  53.             $(this).attr('checked', jQuery.inArray($(this).val(), selectedIds) > -1);
  54.  
  55.         });
  56.     }
  57. </script>
  58. @{ Html.Telerik().Grid<TelerikGridWithCheckboxes.Controllers.Order>()
  59.         .Name("Grid")
  60.         .Columns(columns =>
  61.         {
  62.             columns.Bound(o => o.OrderId)
  63.             .ClientTemplate("<input type='checkbox' id='OrderId' name='OrderId' value='<#= OrderId #>' <#= IsChecked ? checked='checked' : '' #>/>")
  64.                    .Title("")
  65.                    .Width(36)
  66.                    .HtmlAttributes(new { style = "text-align:center" });
  67.  
  68.             columns.Bound(o => o.OrderId).Width(100);
  69.             columns.Bound(o => o.OrderName).Width(200);
  70.         })
  71.         .DataBinding(dataBinding => dataBinding.Ajax()
  72.                 .Select("_CheckBoxesAjax", "Home"))
  73.                 .ClientEvents(c => c.OnDataBound("OnCheckBoxGridDataBound"))
  74.         .Scrollable()
  75.         .Pageable()
  76.         .Render();
  77. }

 

Regards

Ganesh D

ASP.NET # MVC # 20 – Pass/Send Object from Server to JavaScript method on Ajax Form’s onSuccess Event using JSON(JavaScript object notation).

December 22, 2011 Leave a comment

Hi Friends,

Many times we come across the situation where we need to pass the class object from server to the JavaScript function on onSuccess method of Ajax.BeginForm.

OnSuccess gets called only if the request was successful.

In this post we will see how to pass the object from the method on controller to the client side JavaScript method.

-> We have our Ajax Form and JavaScript method as follows:

Code on MVC View
  1. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  2.     <script type="text/javascript">
  3.         function funSuccess(context) {
  4.             debugger;
  5.             var html = context.get_data();
  6.             var obj = $.parseJSON(html);
  7.             alert(obj.SuccessMessage);
  8.         }
  9.     </script>
  10.     <%using (Ajax.BeginForm("PostFormMethod", "Search", new AjaxOptions { OnSuccess = "funSuccess" }))
  11.       { %>
  12.     <h1>
  13.         Hello Ajax</h1>
  14.     <input type="submit" id="btnSubmit" />
  15.     <%} %>
  16. </asp:Content>

 

As you see in the code above we have Ajax.BeginForm  which has PostFormMethod as its Action name and Search as its controller name , and funSuccess is the JavaScript method which is being called on onSuccess event of the form.

-> We have our code on Controller side as follows

Code On Controller
  1. [HttpPost]
  2.         public string PostFormMethod()
  3.         {
  4.             Result obj = new Result();
  5.             obj.SuccessMessage = "Record Saved Successfully!!!";
  6.             System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
  7.              new System.Web.Script.Serialization.JavaScriptSerializer();
  8.             return oSerializer.Serialize(obj);
  9.  
  10.         }

In the above method we are returning the Serialized class object by using the JavaScriptSerializer which is returning the string in serialize format to the onSuccess method of the form.

-> The JavaScript method funSuccess deserialize the object using  $.parseJson jquery function which will return you the object as you see in the following image.

Untitled

 

Thanks,

Hope this will help!!!

Smile

Categories: ASP.NET MVC

ASP.NET MVC # 19 When to use Ajax and When not to use ajax in ASP.NET MVC

November 16, 2011 Leave a comment

Hi Geeks,

AJAX = Asynchronous JavaScript and XML.

AJAX is the art of exchanging data with a server, and update parts of a web page – without reloading the whole page.

In this article we will see where / when to use ajax and when to not in ASP.NET MVC.

1) When to use Ajax

Asynchronous requests have their advantages and can make users feel like they are in control ofyour application rather than the other way round. Some of the advantages include:  
-> Partial Rendering of a Complex Page: If a particular page you’re working on (a portal page, for instance) has a lot of dynamic information on it, it might be advantageous to avoid doing a full postback to the server simply to update a small section of the page. A user may want to filter a list of information,

For example,                                                                                                                               By a selection in a dropdown. Refreshing the entire page (database calls and all) in this case can create a performance bottleneck and give the impression that the site is slow or cumbersome to work with.

-> It Looks Fast: Ajax requests, when properly set up and executed, can be quite fast. When you couple this with the lack of a page blink (from a postback), users tend to come away with the impression that your site is much more responsive even when the response time is roughly the same. This lends to a greater sense of control and interactivity

-> Reduced Server Load: As discussed in the first bullet, careful use of Ajax can reduce the overall load on your server and database. This isn’t confined to complex pages but applies to the entire site operation. If the main functional elements of a page can be confined to smaller
Ajax operations, it can significantly cut down on database and/or server connections.

-> It’s Asynchronous: The fact that Ajax is asynchronous (that’s the A in Ajax) allows you some flexibility in terms of long-running operations or executing things that a user may otherwise not want to wait around for.

For Example ,                                                                                                                       Google’s Gmail application (one of the first major, well-knownAjax applications) is a prime example of clever use of asynchronous requests. Most of the time you’re not aware of the page operations as you read your messages or navigate the site, only while you’re occupied with what’s onscreen, Gmail is constantly checking the server forupdates to conversations (mail messages) and IM status (if you have that enabled).

2) When not to use ajax

-> JavaScript Must Be Enabled on the Client: For many developers, this is a very foreign concept:
A user might actually turn off scripting in his or her browser. There are a lot of reasons
that people do this, not the least of which is security. Clever programming of JavaScript leads
to cross-site scripting attacks, stealing cookies, and even planting various password-stealing
Trojans. Many people disable JavaScript as a matter of habit, and these people will be unable
to use your site if it relies on Ajax.      

-> The Back Button: Usability is a primary feature of every website, and your
browser’s history and Back button are primary considerations. Users should be able to
“undo” their navigation and step backward from whence they came. Ajax doesn’t (normally)
allow for this. If you re-render an entire page using Ajax, or change the display significantly,
you’re presenting information that may not reflect the URL properly. Thus, a user will lose
his or her crumb trail through your site, and navigation becomes somewhat useless.

Hope this helps.. Smile

Thanks,

Categories: ASP.NET MVC

ASP.NET # MVC # 18 – HTML.BeginForm Helper Method

September 30, 2011 Leave a comment

Hi Geeks,

As we have been looking for the helper methods since our last 3 – 4 posts.

Today we will see very important Helper method called Html.Beg inform.

The BeginForm method follows a different pattern from the other helper methods. An HTML form generally starts with a <form> tag, contains a bunch of mark-up in the middle, and then ends with a closing tag.

 
** It wouldn’t be very useful to have to specify the mark-up that goes in between the form start and end tags to the form helper method. Instead, the method uses the disposing pattern to denote the scope
of the form.

An example should clarify what we mean:

 

   <% using(Html.BeginForm())
       {%>
        <label for="firstName"/>
        <
input type="text"name="FirstName"id="firstName" />
        <
input type="submit"value="Save" />
       
<% } %>

In this code sample, you enclose the BeginForm method in a using block. This method returns an instance of MvcForm that implements the IDisposable interface. At the end of the using block, the Dispose method is called, which renders the closing form tag. This provides a convenient approach for implementing HTML blocks in which the closing tag needs to be rendered at the end of a block of arbitrary HTML.

 

It’s an unusual use of a using block, for sure, but being completely biased, we find it quite elegant.For those who find it completely distasteful, you can also use the following approach, which provides a bit of symmetry:

  <% Html.BeginForm(); %>
        <label for="firstName"/>
        <
input type="text" name="FirstName" id="firstName" /> <input type="submit"    value="Save" />
       
<% Html.EndForm(); %>

Thanks,

Hope this will help you.

Categories: ASP.NET MVC

ASP.NET # MVC # 17 – Html.ActionLink and Html.RouteLink Helper Methods

September 23, 2011 9 comments

 

Hi Geeks,

Today we will see Html.ActionLink and Html.RouteLink Helper methods.

I )Html.ActionLink

** The ActionLink method renders a hyperlink (anchor tag) to another Controller action. This method uses the Routing API under the hood to generate the URL. For example, when linking to another action within the same Controller used to render the current View, you can simply specify the action name:

     <%: Html.ActionLink("Link Text", "AnotherAction") %>

     This produces the following markup, assuming the default routes:

     <a href=”/Home/AnotherAction”>LinkText</a>

You can specify a Controller name as the third argument to link to an action of another Controller.For example, to link to the AccountController.Withdraw action, use:

<%: Html.ActionLink("Link Text", "Withdraw", "Account") %>

 

Note :Notice that you specify the Controller name without the Controller suffix. You never specify the Controller’s type name.
In many cases, you have more route parameters than you need to supply in order to choose the correct URL to render for the action link. In that case, you can specify a RouteValueDictionary for the routeValues argument. The following example uses the overload that accepts the anonymous object overload for route values to specify the ID:

 <%: Html.ActionLink("Link Text", "Withdraw", "Account", new {id=34231}, null) %>

** To specify HTML attributes, provide a value for the htmlAttributes argument. This accepts an IDictionary<string, object>, but for ease of use, you can call the overload that accepts an anonymous object:

<%: Html.ActionLink("LinkText", "About", "Account", null,
new {title="withdraw from account"}) %>

II) Html.RouteLink

The ActionLink methods have specific knowledge about ASP.NET MVC Controllers and actions.
Hence, these methods provide convenient overloads that allow the specifying of a controllerName and actionName directly.

The RouteLink methods follow the same pattern as the ActionLink methods but also accept a
route name and do not have arguments for Controller name and action name. For example, the first example ActionLink shown previously is equivalent to the following:

<%: Html.RouteLink("Link Text", new {action="AnotherAction"}) %>

(REFERENCE – Professional.ASP.NET.MVC.2 Wrox publication)

Categories: ASP.NET MVC