Friday 8 January 2010

MVC: Creating custom attributes using "ActionMethodSelectorAttribute".

Hi,

Welcome back!

In MVC application you have encounter many MVC attributes like HandleError and many more. These attributes servers one particular task so that you do not have to re-write the code for for it.

If you want to write your attribute in controller, then how can we do that?
MVC provides one class named ActionMethodSelectorAttribute, which can help us to create our own custom attribute. Let's create our own attrubite "AjaxMethodAttribute". This attribute tests the Ajax request. If the request from Ajax method came, allow the action to execute. The request other than the Ajax should be neglected.


We will create the class named AjaxMethodAttribute inherited from ActionMethodSelectorAttribute.
The class ActionMethodSelectorAttribute has one override method IsValidForRequest which has to be implemented.
Here is our implementation.

public class AjaxMethodAttribute : ActionMethodSelectorAttribute
    {
        ///
        /// Implement IsValidForRequest method as per your need.
        ///
        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
// Check request of Ajax.
            return controllerContext.HttpContext.Request.IsAjaxRequest();
        }
    }

You can now have our custom attribute ready for use. Let's try it.

[AjaxMethodAttribute] public ActionResult AjaxRequest() { ViewData["AjaxCall"] = "Call from Aajx Request"; return View("AjaxRequest"); }

Hope you enjoy this blog. Keep watching for more blogs...

MVC: Handling controller's unknown action using "HandleUnknownAction" method.

Hi,

Welcome back.

Whenever the user for a action / method which does not exists in any controller, the framework shows the error message. How to handle it?

Each controller has one override method named "HandleUnknownAction". You can use it to handle the unknown request. The method accept one parameter actionname.

        /// Method to process unknown action request.
        /// Unknwoan action name

        protected override void HandleUnknownAction(string actionName)
        {
            ViewData["actionName"] = actionName;
            View("Error").ExecuteResult(this.ControllerContext);
        }

You can modify the Error.aspx to show the appropriate message as shown below:


        Sorry, I don't recognize the action <b> <%= Html.Encode(ViewData["actionName"]) %> </b>.


Keep watching my blog for more...

MVC: How to call a view stored in different folder other than the conventional.

Hi,

Welcome back!

In MVC your can return the View which will be view of the same Controller or any other existing controllers. If the view does not exist the framework search the view in Views/Shared folder.


Now, suppose you have to call the view stored in some folder MyViews under the Views folder. There is no controller with name MyViews. How to call this view then?

Here is the solution:

return View("../MyViews/TestView");

You can call this view using relative path as shown above.

Hope you have enjoy this blog.
Keep watching my blog...

Tuesday 15 December 2009

Manipulating Page Content using jQuery

Hi,

In this blog we will learn how to manipulate the page contents using jQuery.
The topics we will learn in today's blog are:
  • Overview of content manipulation:
  • Creating, setting, and getting content
  • Manipulating attributes
  • Inserting Content
  • Wrapping, replacing, removing content
  • Working with CSS information
  • Working with CSS classes
  • Working with CSS positioning
  • Working with CSS sizing information

    Overview of content manipulation:
    • Once you’ve used selectors and filters to retrieve web page content, you usually want to do something with it
    • Sometimes you want to create new content to dynamically add into the page
    • jQuery has functions for creating, copying, deleting, and moving content around, as well as wrapping page content in other content
    • jQuery provides cross-browser support for working with CSS, including positioning and sizing information
    Creating, setting, and getting content:
    • To create new HTML content, you simply pass a string containing new HTML to the $() function:
    Var newHeader = $(“My new header”);
    Var myStr = “My new header”;
    Var newHeader = $(myStr);
    • In addition to this method, you can use the html() and text() methods to get and set content on
    Function
    Purpose
    html()
    Returns the HTML content of the first matched element
    html(newcontent)
    Sets the HTML content of every matched element
    text()
    Returns the text content of the first matched element
    text(newtext)
    Sets the text content for all matched elements
    Manipulating attributes:
    • To inspect or change the value of attribute on elements, use jQuery’s  attr functions
    Function
    Purpose
    attr(name)
    Accesses property on the first matched element. This method makes it easy to retrieve a property value from the first matched element. If the element does not have an attribute with such a name, undefined is returned
    attr(properties)
    Set a series of attributes on all matched element using an object notation syntax. This is the best used for setting large numbers of properties at once
    $(“img”).attr({ src: “/images/hat.gif”, title: “jQuery”, alt: “jQuery Logo”});
    attr(key, value)
    Sets a single property to a value on all matched elements
    attr(key, fn)
    Sets a single property to a computed value, on all matched elements. Instead of supplying a string value, a function is provided that computes the value of the attribute
    removeAttr(name)
    Removes the named attribute from all matched elements
    Inserting Content:
    • JQuery provides several functions for inserting content into the document, both before and after existing page elements
    Function
    Purpose
    append(content)
    Appends content to the inside of every matched element
    appendTo(selector)
    Appends all of the matched elements to another, specified, set of elements
    prepend(content)
    Prepends content to the inside of every matched element
    prependTo(selector)
    Prepends all the matched elements to another, specified, set of elements
    after(content)
    Inserts content after each of the matched elements
    before(content)
    Inserts content before each of the matched elements
    insertAfter(selector)
    Inserts all of the matched elements after another, specified, set of elements
    insertBefore(selector)
    Inserts all of the matched elements before another, specified, set of elements
    Wrapping, replacing, removing content:
    • jQuery can wrap existing content in the page, replace content, copy content, and remove it
    Function
    Purpose
    wrap(html)
    Wraps each matched element with the specified HTML content
    wrap(element)
    Wraps each matched element with the specified element
    wrapAll(html)
    Wraps all the elements in the matched set with the specified HTML content
    wrapAll(element)
    Wraps all the elements in the matched set into a single wrapper element
    wrapInner(html)
    Wraps the inner child contents of each matched element (including text nodes) with an HTML structure
    wrapInner(element)
    Wraps the inner child contents of each matched element (including text nodes) with a DOM structure
    replaceWith(content)
    Replaces all matched elements with the specified HTML or DOM elements
    replaceAll(selector)
    Replaces the elements matched by the specified selector with the matched elements
    empty()
    Removes all child nodes from the set of matched elements
    remove()
    Removes all matched elements from the DOM
    clone()
    Clone matched DOM elements and selects the clones
    clone(bool)
    Clone matched DOM elements, and all their event handlers, and select the clones
    Working with CSS information:
    • jQuery’s CSS functions provide easy, cross-browser access for setting properties and working with positioning and sizing information
    • The css() function allows you to retrieve and set CSS styles for a set of matched elements
    Filter
    Purpose
    css(name)
    Returns the value for the named CSS property for the first matched element
    css(properties)
    Sets the CSS properties of every matched element using an object-notation syntax:
    var cssObj = {
    ‘background-color’  :  ‘#ddd’,
    ‘font-weight’ : ‘ ‘
    ‘color’ : ‘rgb(0, 40, 244)’ }
    $(this).css(cssObj);
    css(property, value)
    Sets a single style property to a value on all matched elements. If a number is provided, it is automatically converted into a pixel value, with the following exception: z-index, font-weight, opacity, zoom, and line-height
    Working with CSS classes:
    • jQuery provides a set of functions for working with CSS classes on page elements
    • Classes can be easily added, removed, toggled, and detected
    CSS Functions
    Purpose
    addClass(class)
    Adds the specified class(es) to each of matched elements
    hasClass(class)
    Returns true if the specified class is present on at least one of the set of matched elements
    removeClass(class)
    Removes all the specified class(es) from the set of matched elements
    toggleClass(class)
    Adds the specified class if it is not present, removes the specified class if it is present
    toggleClass(class, switch)
    Adds the specified class if the switch is true, removed the specified class if the switch is false
    Working with CSS positioning:
    • The CSS positioning functions provide cross-browser support for figuring out the positions of elements
    CSS Functions
    Purpose
    offset()
    Gets the current offset of the first matched element, in pixels, relative to  the document
    offsetParent()
    Returns a jQuery collection with the positioned parent of the first matched element
    position()
    Gets the top and left position of an element relative to its offset parent
    scrollTop()
    Gets the scroll top offset of the first matched element
    scrollTop(val)
    Sets the scroll top offset to the given value on all matched elements
    scrollLeft()
    Gets the scroll left offset of the first matched element
    scrollLeft(val)
    Sets the scroll left offset to the given value on all matched elements
    Working with CSS sizing information:
    • To retrieve cross-browser sizing information for elements, use the jQuery size-related CSS function
    CSS Functions
    Purpose
    height()
    Gets the current computed, pixel, height of the first matched element
    height(val)
    Sets the CSS height of every matched element
    width()
    Gets the current computed, pixel, width of the first matched element
    width(val)
    Sets the CSS width of every matched element
    innerHeight()
    Gets the inner height (excluding the border and including the padding) for the first matched element
    innerWidth()
    Gets the inner width (excluding the border and including the padding) for the first matched element
    outerHeight(margin)
    Gets the outer height (includes the border and padding by default) for the first matched element. If the margin argument is true, then the margin values are also included
    outerwidth(margin)
    Gets the outer width (includes the border and padding by default) for the first matched element. If the margin argument is true, then the margin values are also included
    In the next blog we will learn Working with events using jQuery.

jQuery Selectors and Filters


Hi,
Welcome back.
In the last blog you saw the jQuery overview.
In this blog we will learn:

  • Overview of Selectors and Filters
  • Using basic jQuery selectors
  • Using filters
  • Using basic jQuery filters
  • Attribute filters
  • Content and Visibility filters
  • Child filters
  • Form selectors
  • Traversing Document Information
  • jQuery  statement chaining


Overview of Selectors and Filters:
  • jQuery selectors and filters retrieve contents from the documents so it can be manipulated using other functions
-          jQuery selectors return an array of objects that match the selection criteria
-          jQuery filters operates on a selectors to further refine the results array that the selector returns
  • This array is not a set of DOM elements
  • It is a collection of jQuery objects that provide a large number of predefined functions for further operating on the objects
Using basic jQuery selectors
  • CSS-style selectors and filters are based on familiar CSS syntax, and work pretty much the same way as CSS does
  • The CSS selectors listed here correspond directly to their CSS counterpart s
Selectors
Purpose
tagname
Finds all elements that are named tagname
#identifier
Finds all elements with ID of identifier
.className
Finds all elements that have class attribute with the value of className
tag.className
Get elements of type tag that have a class attribute with the value of className
tag#id.className
Retrieves the tag element that has an ID of id and a class attribute with the value of className
*
Finds all of the elements on the page
  • The hierarchy and combination selectors allow you to get a little more advanced in selecting page content
  • You can select elements based on hierarchical relationships or on a series of comman criteria
Selector
Purpose
selector, selector
Finds all of the specified selectors
.class1.class2
Finds all elements with both .class1 and .class2 applied
Parent>child
Finds all child elements that are direct children of elements of type parent
Ancestor descendant
Finds all descendant elements that are contained within elements of type ancestor
Prev + next
Finds all next elements that are next to prev element
Prev ~ siblings
Finds all sibling elements that come after prev and match the siblings selector

Using filters
  • Filters work with selectors to provide even more fine-grained control over how elements are selected in the document
  • jQuery filters fall into six different categories
  1. Basic: Provides basic filtering, like getting the first, last, and even- and odd-numbered items in a returned set
  2. Content: Filters a set of elements based on the content, like whether an element contains a particular string
  3. Visibility: Filters a set of elements using the visibility setting of each element as a test
  4. Attribute: Examines a given attribute on an element to determine whether it should be filtered out
  5. Child: Selects elements based upon their relationship with their parent element
  6. Form: Provides specialized filters that operate on form elements
Using basic jQuery filters:
  • You can refine a selector by including elements that match certain conditions, like position or index
Filter
Purpose
:first
Selects only the first instance of the selector’s returned set
:last
Selects only the last instance of the selector’s returned set
:even
Selects only even-numbered elements in the selector’s returned set
:odd
Selects only odd-numbered elements in the selector’s returned set
:eq(n)
Filters out elements that are not positioned at the given index
:gt(n)
Includes elements that are past the given index
:lt(n)
Includes elements that are before the given index
:header
Selects all header elements (H1, H2, H3, etc)
:animated
Selects all elements that are currently being animated in some way
:not(selector)
Includes elements that do not match the given selector

Attribute filters:

  • You can filter the results of a selector statement based on attribute content
Filter
Purpose
[attribute]
Includes elements in the result set if they have the specified attribute
[attribute=value]
Includes elements in the result set if they have the specified attribute and it has the given value
[attribute!=value]
Includes elements in the result set only if they have the specified attribute and it doesn’t have the given value
[attribute^=value]
Includes elements that have the specified attribute and it starts with the specified value
[attribute$=value]
Includes elements that have the specified attribute and it ends with the specified value
[attribute*=value]
Includes elements that have the specified attribute and it contains the specified value
[attrFilter1][attrFilterN]
Includes elements that match all of the specified attribute filters

 Content and Visibility filters:
  • You can examine the content of selected elements or their visibility property to determine whether they should be included or excluded from the final set
Content filter
Purpose
:contains(text)
Filters the selection to only include elements that contain the text string
:empty
Filters the selection to only include empty elements
:has(selector)
Matches elements that contain at least one element that has the specified selector
:parent
Matches all elements that are parents (i.e. they contain at least one other element, including text)

Visibility filter
Purpose
:visible
Filters the selection to only include visible elements
:hidden
Filters the selection to only include hidden elements

Child filters:
  • You can refine a selector by examining the relationship each element has with its parent element
Filter
Purpose
:nth-child(index)
:nth-child(even)
:nth-child(odd)
:nth-child(equation)
Matches elements at index, or even or odd increments, or who match an equation of the form Xn+M (e.g., 2n or 3n+1)
:first-child
Matches elements who are the first child of their parent
:last-child
Matches elements who are the last child of their parent
:only-child
Matches elements who are the only child of their parent

Form selectors:

  • You can use form selectors to deal with form elements
  • They work like other selectors but start with a colon (:) like a regular filter
Selector
Purpose
:input
Finds all input, select, textarea, and button elements
:text
Finds all text elements
:password
Finds all password elements
:radio
Finds all radio button elements
:checkbox
Finds all checkbox elements
:submit
Finds all submit elements
:reset
Finds all reset elements
:image
Finds all image elements
:button
Finds all button elements
:file
Finds all file upload elements
  • You can perform additional filtering of form elements, such as whether items are checked, selected, or enabled
Selector
Purpose
:enabled
Matches all form elements that are enabled
:disabled
Matches all form elements that are disabled
:checked
Matches all form elements that are checked (radiobuttons and checkboxes)
:selected
Matches all form elements that are selected

Traversing Document Information:
  • You can traverse the information returned from a document easily
Function / Property
Purpose
Size(), length
The number of elements in the jQuery result set
get()
Returns an array of all matched DOM elements. Useful if you need to operate on the DOM elements themselves instead of using built-in jQuery functions
get(index)
Access a single matched DOM element at a specified index in the matched set
find(expression)
Searched for descendent elements that match the specified expression
each(fn)
Execute a function within the context of every matched element

jQuery  statement chaining:
  • One of jQuery’s most powerful features is its ability to chain multiple functions together to perform several operations in one line of code
$(selector).fn1().fn2().fn3();
                     statement chain
In the next blog we will learn how to manipulate the page contents using jQuery.