22 March 2015

JQuery Quick Reference

JQuery Quick Reference

1.    JQuery
            jQuery is a JavaScript Library.
jQuery greatly simplifies JavaScript programming.
jQuery uses CSS syntax to select elements.

  2. Uses
The jQuery library contains the following features:

            HTML/DOM manipulation
            CSS manipulation
            HTML event methods
            Effects and animations
            AJAX
            Utilities
Notes:
If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network).
$(document).ready(function(){
   // jQuery methods go here...
});
or
$(function(){
   // jQuery methods go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).

3. JQuery Selector
$("*")     Selects all elements    
$(this)     Selects the current HTML element    
$("p.intro")     Selects all elements with class="intro"    
$("p:first")     Selects the first element     Try it
$("ul li:first")     Selects the first
  • element of the first
          
  • $("ul li:first-child")     Selects the first
  • element of every
          
  • $("[href]")     Selects all elements with an href attribute     Try it
    $("a[target='_blank']")     Selects all elements with a target attribute value equal to "_blank"    
    $(":button")     Selects all
    $("tr:even")     Selects all even elements    
    $("tr:odd")     Selects all odd elements

    4.

    click()
    $("p").click(function(){  // When a click event fires on a element
                $(this).hide();   //   hide the current element
    });
    dblclick()
    $("p").dblclick(function(){
                $(this).hide();
    });
    mouseenter()
     $("#p1").mouseenter(function(){
                alert("You entered p1!");
    });

    hover()
    $("#p1").hover(function(){
                alert("You entered p1!");
    },

    focus()
    $("input").focus(function(){
                $(this).css("background-color", "#cccccc");
    });
    blur()
    $("input").blur(function(){
                $(this).css("background-color", "#ffffff");
    });
    jQuery toggle()
    Shown elements are hidden and hidden elements are shown:
    $("button").click(function(){
                $("p").toggle();
    });

    5. jQuery Callback Functions         
    JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.
    A callback function is executed after the current effect is finished.

    $("button").click(function(){
                $("p").hide("slow", function(){
                alert("The paragraph is now hidden");
                });
    });
    function do_a( callback ){
      setTimeout( function(){
                // simulate a time consuming function
                console.log( '`do_a`: this takes longer than `do_b`' );

                // if callback exist execute it
                callback && callback();
      }, 3000 );
    }

    function do_b(){
      console.log( '`do_b`: now we can make sure `do_b` comes out after `do_a`' );
    }

    do_a( function(){
      do_b();
    });

    Example :
    `do_a`: this takes longer than `do_b`
    `do_b`: now we can make sure `do_b` comes out after `do_a`

    6. jQuery - Chaining

    Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.
    $("#p1").css("color", "red")
      .slideUp(2000)
      .slideDown(2000);

    7. Get Attributes - attr()
                $("button").click(function(){
                alert($("#w3s").attr("href"));
                });
    8.jQuery - Set Content and Attributes
                text() - Sets or returns the text content of selected elements
                html() - Sets or returns the content of selected elements (including HTML markup)
                val() - Sets or returns the value of form fields

    $("#btn1").click(function(){
                $("#test1").text("Hello world!");
    });
    $("#btn2").click(function(){
                $("#test2").html("Hello world!");
    });
    $("#btn3").click(function(){
                $("#test3").val("Dolly Duck");
    });

    9.Set Attributes - attr()
    The jQuery attr() method is also used to set/change attribute values.

     $("button").click(function(){
                $("#w3s").attr("href", "http://www.w3schools.com/jquery");
    });

    10.jQuery - Add Elements
        With jQuery, it is easy to add new elements/content.
       
                append() - Inserts content at the end of the selected elements
                prepend() - Inserts content at the beginning of the selected elements
                after() - Inserts content after the selected elements
                before() - Inserts content before the selected elements

    11.jQuery - Remove Elements

        With jQuery, it is easy to remove existing HTML elements.

                remove() - Removes the selected element (and its child elements)
                empty() - Removes the child elements from the selected element


    jQuery remove() Method
    The jQuery remove() method removes the selected element(s) and its child elements.
    $("#div1").remove();

    jQuery empty() Method
    The jQuery empty() method removes the child elements of the selected element(s).
    $("#div1").empty();

    Filter the Elements to be Removed
    $("p").remove(".italic");

    jQuery - Get and Set CSS Classes

    With jQuery, it is easy to manipulate the CSS of elements.


                addClass() - Adds one or more classes to the selected elements
                removeClass() - Removes one or more classes from the selected elements
                toggleClass() - Toggles between adding/removing classes from the selected elements
                css() - Sets or returns the style attribute

    jQuery addClass() Method
    $("button").click(function(){
                $("h1, h2, p").addClass("blue");
                $("div").addClass("important");
    });

    jQuery removeClass() Method

    $("button").click(function(){
                $("h1, h2, p").removeClass("blue");
    });

    jQuery toggleClass() Method

    $("button").click(function(){
                $("h1, h2, p").toggleClass("blue");
    });

    jQuery css() Method

    Return a CSS Property
    The following example will return the background-color value of the FIRST matched element:
    $("p").css("background-color");

    Set a CSS Property
    $("p").css("background-color", "yellow");

    Set Multiple CSS Properties
    The following example will set a background-color and a font-size for ALL matched elements:
    $("p").css({"background-color": "yellow", "font-size": "200%"});

    jQuery - Dimensions

    jQuery has several important methods for working with dimensions:

                width()
                height()
                innerWidth()
                innerHeight()
                outerWidth()
                outerHeight()


    jQuery Traversing - Ancestors
    An ancestor is a parent, grandparent, great-grandparent, and so on.
    With jQuery you can traverse up the DOM tree to find ancestors of an element.

    jQuery parent() Method
    The parent() method returns the direct parent element of the selected element.
    This method only traverse a single level up the DOM tree.

    jQuery parents() Method
    The parents() method returns all ancestor elements of the selected element, all the way up to the document's root element ().
    $(document).ready(function(){
                $("span").parents();
    });
    The following example returns all ancestors of all elements that are
      elements:
    $(document).ready(function(){
                $("span").parents("ul");
    });

    jQuery parentsUntil() Method
    The parentsUntil() method returns all ancestor elements between two given arguments.
    $(document).ready(function(){
                $("span").parentsUntil("div");
    });

    jQuery Traversing - Descendants

    A descendant is a child, grandchild, great-grandchild, and so on.
    With jQuery you can traverse down the DOM tree to find descendants of an element.

    jQuery children() Method

    The children() method returns all direct children of the selected element.
    $(document).ready(function(){
                $("div").children();
    });

    jQuery find() Method
    The find() method returns descendant elements of the selected element, all the way down to the last descendant.
    $(document).ready(function(){
                $("div").find("span");
    });


    The following example returns all descendants of
    :
    $(document).ready(function(){
                $("div").find("*");
    });


    jQuery siblings() Method
    The following example returns all sibling elements of

    :

    $(document).ready(function(){
                $("h2").siblings();
    });
    jQuery next() Method

    The next() method returns the next sibling element of the selected element
    $(document).ready(function(){
                $("h2").next();
    });

    jQuery nextAll() Method
    The nextAll() method returns all next sibling elements of the selected element.
    $(document).ready(function(){
                $("h2").nextAll();
    });
    jQuery nextUntil() Method
    The nextUntil() method returns all next sibling elements between two given arguments.

    $(document).ready(function(){
                $("h2").nextUntil("h6");
    });
    jQuery first() Method
    The first() method returns the first element of the selected elements.
    $(document).ready(function(){
                $("div p").first();
    });

    jQuery last() Method
    The last() method returns the last element of the selected elements.
    $(document).ready(function(){
                $("div p").last();
    });
    jQuery eq() method
    The eq() method returns an element with a specific index number of the selected elements.
    $(document).ready(function(){
                $("p").eq(1);
    });

    jQuery filter() Method
    The following example returns all elements with class name "intro":
    $(document).ready(function(){
                $("p").filter(".intro");
    });

    jQuery not() Method
    The following example returns all elements that do not have class name "intro":
    $(document).ready(function(){
                $("p").not(".intro");
    });

    jQuery - The noConflict() Method
    If two different frameworks are using the same shortcut, one of them might stop working.
    The jQuery team have already thought about this, and implemented the noConflict() method.
    The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it.

    $.noConflict();
    jQuery(document).ready(function(){
                jQuery("button").click(function(){
                jQuery("p").text("jQuery is still working!");
                });
    });

    JQuery
    //MVC JQuery Ajax
    $('#learnitem-form').ajaxSubmit({
      data : {
                data1: data1,
                data2: data2,

                },
      success : function(result){
      //success
                },
      error : function(){
      //error
      }
    });

    Posting Javascript Object


    type     This is type of HTTP Request and accepts a valid HTTP verb. POST is the option illustrated in this article.
    url     This is the location of the resource that the request will be made to.
    data     This is the actual data to be sent as part of the request.
    contentType     This is the content type of the request you are making. The default is 'application/x-www-form-urlencoded'.
    dataType     This is the type of data you expect to receive back. Accepted values are text, xml, json, script, html jsonp. If you do not provide a value, jQuery will examine the MIME type of the response and base its decision on that.






    MVC Interview Question in Dotnet

    MVC Interview Question in Dotnet

    1.     What is MVC ?
    MVC is an architectural pattern which separates the representation and user interaction.
    M - Model -  Application business logic is in the Model
    V - View - Views represent the user interface, with which the end users interact.
    C - Controller - Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface.

    2. Advantages of MVC
    1.     ASP.NET MVC views are light weight, as they do not use viewstate.
    2.     Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
    3.     Complex application can be easily managed by the developer.
    4.     In Razor view engine using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks.
    5.     Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.). Bundling that makes it easy to combine or bundle multiple files into a single file.
    6.     Minification performs a variety of different code optimizations to scripts or css, such as removing unnecessary whitespace and comments and shortening variable names to one character.
    3. MVC Application Life cycle
    MVC application life cycle has two main phases
    Creating the request object and sending our response to the browser.
    Creating the request Object
    Step 1: Fill route : - MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.
    Step 2: Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.
    Step 3 Request context created: - The “RouteData” object is used to create the “RequestContext” object.
    Step 4 Controller instance created: - This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.
    Creating Response object: - This phase has two steps executing the action and finally sending the response as a result to the view.

    4.Routing in MVC
    Routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. At runtime, Routing engine use the Route table for matching the incoming request's URL pattern against the URL patterns defined in the Route table. You can register one or more URL patterns to the Route table at Application_Start event.

    routes.MapRoute(
                   "View", // Route name
                   "View/ViewCustomer/{id}", // URL with parameters
                   new { controller = "Customer", action = "DisplayCustomer",
    id = UrlParameter.Optional }); // Parameter defaults

    The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application start event.

    5.HTML helpers in MVC
    HTML helpers help you to render HTML controls in the view. For instance if you want to display a HTML textbox on the view , below is the HTML helper code.
    Copy Code

    <%= Html.TextBox("LastName") %>
    6. Difference between HTML.TextBoxFor and HTML.TextBox
    Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t
    Html.TextBox("CustomerCode")
    Html.TextBoxFor(m => m.CustomerCode)

    7.Attribute based routing in MVC
    This is a feature introduced in MVC 5. By using the "Route" attribute we can define the URL structure.
    public class HomeController : Controller
    {
           [Route("Users/about")]
           public ActionResult GotoAbout()
           {
               return View();
           }
    }
    Most of the time developers code in the action methods. Developers can see the URL structure right upfront rather than going to the “routeconfig.cs” and see the lengthy codes.

    8. Navigate from one view to another using a hyperlink?
    <%= Html.ActionLink("Home","Gotohome") %>
    Home - Controller
    Gotohome - Action

    9. Restrict MVC actions to be invoked only by GET or POST
    We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the DisplayCustomer action can only be invoked by HttpGet. If we try to make HTTP POST on DisplayCustomer, it will throw an error.

    [HttpGet]
    public ViewResult DisplayCustomer(int id)
    {
        Customer objCustomer = Customers[id];
        return View("DisplayCustomer",objCustomer);
    }

    10.ViewData, ViewBag and TempData

    ASP.NET MVC offers us three options ViewData, ViewBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility.
    Helps to maintain data when you move from controller to view.
    ViewData requires typecasting for complex data type and check for null values to avoid error and ViewBag doesn’t require typecasting for complex data type.
    ViewBag & ViewData Example:

    public ActionResult Index()
                    ViewBag.Name = "Arun Prakash";
                    return View();   
    }

    public ActionResult Index() 
    {
                    ViewData["Name"] = "Arun Prakash";
                    return View();
    }

    In View, we call like below:

    @ViewBag.Name  
    @ViewData["Name"]
    TempData:

    Helps to maintain data when you move from one controller to another controller or from one action to other action. In other words when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables. TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only.

    It requires typecasting for complex data type and check for null values to avoid error.
    So if “TempData” is once read it will not be available in the subsequent request.

    11.Partial views in MVC?
    Partial view is a reusable view (like a user control) which can be embedded inside other view.

    12.Validations in MVC?
    Data annotations are nothing but attributes which can be applied on model properties.

    Types
    [Required]
    [StringLength(50, MinimumLength = 2)]
    [Range(15, 100)]

    Data type
    The data type annotation can be used to specify the data type for validation. The information may also be used as UI hint later in rendering process.
    Copy Code

    [Url]
    public string url { get; set; }
    [Phone]
    public string phone { get; set; }
    [DataType(DataType.Date)]
    public DateTime updatedate { get; set; }

    [DataType(DataType.PhoneNumber)]
    public string phone { get; set; }
    public class Customer
    {
        [Required(ErrorMessage="Customer code is required")]
        public string CustomerCode
        {
            set;
            get;
        }
    }

    <% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
    { %>
    <%=Html.TextBoxFor(m => m.CustomerCode)%>
    <%=Html.ValidationMessageFor(m => m.CustomerCode)%>

    <%}%>
    Later in the controller we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take actions.

    public ActionResult PostCustomer(Customer obj)
    {
        if (ModelState.IsValid)
        {
            obj.Save();
            return View("Thanks");
        }
        else
        {
            return View("Customer");
        }
    }

    13.Can we display all errors in one go?
    Yes, we can; use the ValidationSummary method from the Html helper class.
    <%= Html.ValidationSummary() %>

    14. Ajax in MVC

    Implement Ajax using Ajax libraries
    function GetData()
    {
                    var url = "/MyAjax/getCustomer";
                    $.post(url, function (data)
                    {
                    $("#txtCustomerCode").val(data.CustomerCode);
                    $("#txtCustomerName").val(data.CustomerName);
                    }
                    )
    }
    implement AJAX by using the “AJAX” helper library


    <%
       var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};                    
    %>
    <% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>


    <%} %>

    15.Difference between ActionResult and ViewResult?

    ActionResult is an abstract class while ViewResult derives from the ActionResult class.
    ActionResult has several derived classes like ViewResult, JsonResult, FileStreamResult, and so on.
    Depending on the flag (IsHtmlView) it will either return a ViewResult or JsonResult.

    public ActionResult DynamicView()
    {
       if (IsHtmlView)
                    return View(); // returns simple ViewResult
       else
                    return Json(); // returns JsonResult view
    }

    16.Different types of results in MVC?

    There 12 kinds of results in MVC, at the top is the ActionResult class which is a base class that can have 11 subtypes as listed below:

                    1.ViewResult - Renders a specified view to the response stream
                    2.PartialViewResult - Renders a specified partial view to the response stream
                    3.EmptyResult - An empty response is returned
                    4.RedirectResult - Performs an HTTP redirection to a specified URL
                    5.RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine,  based on given route data
                    6.JsonResult - Serializes a given ViewData object to JSON format
                    7.JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
                    8.ContentResult - Writes content to the response stream without requiring a view
                    9.FileContentResult - Returns a file to the client
                    10.FileStreamResult - Returns a file to the client, which is provided by a Stream
                    11.FilePathResult - Returns a file to the client


    17. Areas in MVC?
    Group the  controller classes into logical section
    18. MVC Scaffolding
    Scaffolding is a technique in which the MVC template helps to auto-generate CRUD code. CRUD stands for create, read, update and delete.
    19.Multiple Submit buttons pointing to multiple actions in a single MVC view
    HTML Way








    Ajax Way







    20. MVC Ajax Example
    //MVC JQuery Ajax

    $('#learnitem-form').ajaxSubmit({

      data : {
              data1: data1,
              data2: data2,

             },

      success : function(result){
      //success
             },
      error : function(){
      //error
      }
    });
    20. MVC Action Filters
    ASP.NET MVC provides Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.

    Authorization filter, which makes security decisions about whether to execute an action method, such as performing authentication or validating properties of the request.

    Action filter, which wraps the action method execution. This filter can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method

    OnActionExecuting - Runs before execution of Action method.
    OnActionExecuted - Runs after execution of Action method.
    OnResultExecuting - Runs before content is rendered to View.
    OnResultExecuted - Runs after content is rendered to view.



    Result filter, which wraps execution of the ActionResult object. This filter can perform additional processing of the result, such as modifying the HTTP response.

    Exception filter, which executes if there is an unhandled exception thrown somewhere in action method, starting with the authorization filters and ending with the execution of the result. Exception filters can be used for tasks such as logging or displaying an error page.

    21. MVC Custom Filters
    When you request any page into MVC Application, it will go through the Routing Architecture. Your Routing system will decide your URL pattern. The default routing algorithm is like {controller}/ {action}/ {id} patterns. But it can be possible to change that pattern using Custom Routes.

    When you create a Custom Route, you can also include route constraints. These constraints are used to restrict the requests to match routes. There are three basic types of constraints:

    1.     Regular Expression Constraints - check the pattern of the Route and prevent invalid requests
    2.     HttpMethod Constraints - You can match route with any type of the HTTP operation like POST, GET, etc. you want to prevent user to access particular URL when GET operation occurs but not POST operation occurs.
    //Custom Route With HttpMethod Constraint
                routes.MapRoute(
                    "HttpMethodConstraintRoute",
                    "Blog/Insert",
                    new { Controller = "Blog", action = "Insert" },
            new { method = new HttpMethodConstraint("GET") });

     3. CatchAllRoutes- Suitable for the dynamic URL, But if you want to match your URL, regardless of the number     of the segments for that, we have to create Catch-All Parameter.

    22.Action Results - ActionResult method works as a return type of any controller method in the MVC. It acts like the base class of Result classes. It is used to return the models to the Views, file streams and also redirect to the controllers.
    23.Razor View Engine VS Web Form(ASPX) View Engine

    1.     Razor Engine is an advanced view engine that was introduced with MVC3.
    Web Form Engine is the default view engine for the Asp.net MVC that is included with Asp.net MVC from the beginning.

                 2. The file extensions used with Razor Engine are different from Web Form Engine. It has .cshtml (Razor
                with  C#) or .vbhtml (Razor with VB) extension for views, partial views, editor templates and for layout pages.

    3. The file extensions used with Web Form Engine are also like Asp.net Web Forms. It has .aspx         extension     for  views, .ascx extension for partial views & editor templates and .master extension for layout/master pages.

                   4. Razor has new and advance syntax that are compact, expressive and reduces typing.
                   Web Form Engine has the same syntax like Asp.net Web Forms uses for .aspx pages.

    5. Razor syntax are easy to learn and much clean than Web Form syntax. Razor uses @ symbol to make the code like as:
    @Html.ActionLink("SignUp", "SignUp")
    Web Form syntax are borrowed from Asp.net Web Forms syntax that are mixed with html and sometimes make a view messy. Webform uses <% and %> delimiters to make the code like as:
    <%: Html.ActionLink("SignUp", "SignUp") %>

    6.By default, Razor Engine prevents XSS attacks(Cross-Site Scripting Attacks) means it encodes the script or html tags like <,> before rendering to view.
    Web Form Engine does not prevent XSS attacks means any script saved in the database will be fired while rendering the page

    7. Razor Engine is little bit slow as compared to Webform Engine.
    Web Form Engine is faster than Razor Engine.

    8. Razor Engine, doesn't support design mode in visual studio means you cannot see your page look and feel.
    Web Form engine support design mode in visual studio means you can see your page look and feel without running the application.

    9. Razor Engine support TDD (Test Driven Development) since it is not depend on System.Web.UI.Page class.
    Web Form Engine doesn't support TDD (Test Driven Development) since it depend on System.Web.UI.Page class which makes the testing complex.




    25 October 2014

    MVC Model Binding Vulnerability

    MVC Model Binding Vulnerability
    Reference Link:
    For example User Entity
    public class User
    {
        public string FirstName { get; set; }
        public bool IsAdmin { get; set; }
    }
    When you want to let a regular user change their first name, you give them the following form.
    @using (Html.BeginForm()) {
       
         @Html.EditorFor(model => model.FirstName)
            
        
    }
    There is no input in the form to let a user set the IsAdmin flag, but this won't stop someone from crafting an HTTP request with IsAdmin in the query string or request body. Maybe they saw the "IsAdmin" name somewhere in a request displaying account details, or maybe they just got lucky and guessed the name.
    composing the attack
    If you use the MVC model binder with the above request and the previous model, then the model binder will happily move the IsAdmin value into the IsAdmin property of the model. Assuming you save the model values into a database, then any user can become an administrator by sending the right request. It's not enough to leave an IsAdmin input out of the edit form.
    Fortunately, there are at least 6 different approaches you can use to remove the vulnerability. Some approaches are architectural, others just involve adding some metadata or using the right API.

    Weakly Typed Approaches

    The [Bind] attribute will let you specify the exact properties a model binder should include in binding (a whitelist).
    [HttpPost]
    public ViewResult Edit([Bind(Include = "FirstName")] User user)
    {
        // ...
    }
    Alternatively, you could use a blacklist approach by setting the Exclude parameter on the attribute.
    [HttpPost]
    public ViewResult Edit([Bind(Exclude = "IsAdmin")] User user)
    {
        // ...
    }
    If you prefer explicit binding with the UpdateModel and TryUpdateModel API, then these methods also support whitelist and blacklist parameters.
    [HttpPost]
    public ViewResult Edit()
    {
        var user = new User();
        TryUpdateModel(user, includeProperties: new[] { "FirstName" });
        // ...
    }

    Strongly Typed Approaches

    TryUpdateModel will take a generic type parameter.  You can use the generic type parameter and an interface definition to restrict the model binder to a subset of properties.
    [HttpPost]
    public ViewResult Edit()
    {
        var user = new User();
        TryUpdateModel<IUserInputModel>(user);
    
        return View("detail", user);
    }
    This assumes your interface definition looks like the following.
    public interface IUserInputModel
    {
        string FirstName { get; set; }
    }
    Of course, the model will also have to implement the interface.
    public class User : IUserInputModel
    {
        public string FirstName { get; set; }
        public bool IsAdmin { get; set; }
    }
    There is also a [ReadOnly] attribute the model binder will respect. ReadOnly metadata might be want you want to use if you never want to bind the IsAdmin property. (Note: I remember ReadOnly not working in MVC 2 or MVC 1, but it is working in 3 & 4 (beta)).
    public class User 
    {
        public string FirstName { get; set; }
    
        [ReadOnly(true)]
        public bool IsAdmin { get; set; }
    }

    An Architectural Approach

    Put user input into a model designed for user input only.
    public class UserInputViewModel
    {
        public string FirstName { get; set; }
    }
    In this approach you'll never bind against business objects or entities, and you'll only have properties available for the input you expect. Once the model is validated you can move values from the input model to the object you use in the next layer of software.
    Based upon our convenience we can choose the approach.

    12 October 2014

    Revealing Module Pattern in Javascript

    Revealing Module Pattern in Javascript


    JavaScript Module pattern provides a way to wrap public, private methods (and variable) into a single entity and exposing only the public members to the world outside of module. This allows faster namespace resolution, avoid collision of the methods/variables with other global APIs since the namespace isn't populated with all many functions, and obviously provides cleaner code.

    CalcModule = (function(){
                var mem = new Array(); //private variable

                var storeInMemory = function(val) {  //private function
                    mem.push(val);
                };

                var add = function(a, b) {
                            var result = a + b;
                            storeInMemory(result); //call to private function
                            return result;
                        };

                var sub = function(a, b) {
                            var result = a - b;
                            storeInMemory(result); //call to private function
                            return result;
                        };

                var retrieveFromMemory = function() {
                            return mem.pop();
                        };

                return {
                    add: add,
                    sub: sub,
                    popMemory: retrieveFromMemory
                };
    })();

    Instead we define all the functions public or not in the same way, and then in the return statement create a new object and add properties to it.

    Advantages of Revealing Module pattern in Javascript
    1. Consistent coding style inside the module for both private and public members.
    2. Better control on the name of the public API, i.e., if it is required to change the name of add()         method to addition(), all we need to do is change the name in the return statement without effecting    the function name inside the module.
    3.Control on what to make public, just adding/removing the properties in return statement is sufficient.
    4.As always, cleaner code.

    reference : http://viralpatel.net/blogs/javascript-module-pattern/

    26 July 2014

    Restrict MVC actions to be invoked only by GET or POST

    Restrict MVC actions to be invoked only by GET or POST

    We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the DisplayCustomer action can only be invoked by HttpGet. If we try to make HTTP POST on DisplayCustomer, it will throw an error.


    [HttpGet]
    public ViewResult DisplayCustomer(int id)
    {
        Customer objCustomer = Customers[id];
        return View("DisplayCustomer",objCustomer);
    }


    Routing in MVC

    Routing in MVC

    Routing helps you to define a URL structure and map the URL with the controller.

    The route mapping code is written in the “global.asax” file.

    For Example

    routes.MapRoute(
                   "View", // Route name
                   "View/ViewCustomer/{id}", // URL with parameters
                   new { controller = "Customer", action = "DisplayCustomer",

    id = UrlParameter.Optional }); // Parameter defaults

    When a user types “http://localhost/View/ViewCustomer/”, it goes to the “Customer” Controller and invokes the DisplayCustomer action. This is defined by adding an entry in to the routes collection using the maproute function. Below is the underlined code which shows how the URL structure and mapping with controller and action is defined.

    Note:
    We can map multiple URL'S to the same action.
    Add two entries with different key names and specify the same controller and action.





    Difference between HTML.TextBox vs HTML.TextBoxFor

    Difference between HTML.TextBox vs HTML.TextBoxFor

    Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” is not strongly typed

    Html.TextBox("Name")

    Below is “Html.TextBoxFor” code which creates HTML textbox using the property name ‘Name” from object “m”.


    Implementing OAuth validation in a Web API

     I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...