Friday, January 15, 2016

Ajax.BeginForm Example - ASP.NET MVC

In this example I use an ajax form to load search results.

1) In my view I add the Ajax form.

The form invokes the "SearchResult" action

@using (Ajax.BeginForm("SearchResult", "Search", new AjaxOptions
{
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "searchResults"
}))
{
    <input type="text" name="q" />
    <input type="submit" value="Search" />  
}

<table id="searchResults">

</table>

2) The Action

public PartialViewResult SearchResult(string q)
        {
            var books = BookDB.GetBooks().Where(r => r.Name.Contains(q) || String.IsNullOrEmpty(q)).Take(10);
            return PartialView("_SearchResults", books);
        }

3)  The partial view to display search results

@using MvcBookReview.Infrastructure
@model IEnumerable<MvcBookReview.Models.BookReview>

<table id="searchResults">
    @foreach(var item in Model)
    {
    <tr>
        <td>
            <table>
                <tr>
                    <td><b>Book:</b> @item.Name</td>
                </tr>
                <tr>
                    <td><b>Rating:</b> @item.Rating</td>
                </tr>
            </table>
        </td>
        <td>
            <div class="bookitem">
                @Html.Image(item.ImageUrl, item.AlternateText)
            </div>
        </td>
    </tr>
    }
</table>

Note: Here I use the custom helper created in an earlier post


The Result: 
From left to right
    1) Search all
    2) Search text = "TinTin"
    3) Search text = "Asterix"


Thursday, January 14, 2016

Anti Cross Site Scripting Library - .NET

In case you have enable users to input html without validating and display without encoding (Eg: Using @Html.Raw), then you make the site prone to XSS. .NET provides an Anti XSS library to use in such scenarios.

1) Download the library through VS NuGet package manager


2) The following DLL's will be added in the solution reference










3) Use the library to remove all XSS causing scripts that may be included in  the user inputs.

Example:
review.Body = Sanitizer.GetSafeHtmlFragment(review.Body);

Wednesday, January 13, 2016

Ajax ActionLink - ASP.NET MVC

In this example I create an Ajax Action Link. Using the ActionLink load a partial view to the page.

1. In my view I create an ActionLink as

<div  id="latestReview">
    @Ajax.ActionLink("Get Latest Review", "LatestReview", new AjaxOptions
{
    UpdateTargetId = "latestReview",
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "GET",
    LoadingElementId = "progress"
})
</div >

also add another div for later use

<div id="progress">
    <img src="@Url.Content("~/Images/loading.gif")" />
</div >


In @Ajax.ActionLink()

  • The second parameter is the Action method which will be invoked on click
  • The third parameter specifies the ajax options


In the AjaxOption

  • The "UpdateTargetId" specifies the location in the DOM to display the result.
  • The "InsertionMode" provides the options such as Before, after or replace.
  • The "LoadingElementId" specifies the "progress" div to display until the view is partial view loaded

2. Next, in the controller create an Action method

In this example I omit the DB calls, instead create a dummy object of type BookReview. Note the return is a partial view


        public PartialViewResult LatestReview()
        {
            var modelTwo = new BookReview()
            {
                Name = "Samson",
                Rating = 7
            };
            Thread.Sleep(2000);
            return PartialView("_Review", modelTwo);
        }

a delay is created to show the "LoadingElementId" behaviour in the link

3. Create the partial view

@model MvcBookReview.Models.BookReview

<div class="review">
    <table class="rating">
        <tr class="ratinghead"><th>User</th><th>Rating</th></tr>
        <tr><td>@Model.Name</td><td>@Model.Rating</td></tr>
    </table>       
</div>

Note:
If you don't have the JQuery unobtrusive ajax library ("jquery.unobtrusive-ajax.min.js")in your solution, the ajax action link would not work properly. Add it to your solution through the Visual Studio Nuget Package Manager.

Result
The 3 stages: link, while processing action, result


When you have a look at the link through the browser's developer tool you will see something like this


Tuesday, January 12, 2016

Razor Helper - ASP.NET MVC

There are two ways to implement this

Razor helper can be added directly to a view. 
For an instance lets go into the _Layouts.cshtml view and add the below Razor helper after the </html> tag

@helper Script(string scriptName) { 
    <script src="@Url.Content("~/Scripts/" + scriptName)" type="text/javascript"></script>
    }

Now at the top of the page within the <head> tag you could reference the razor helper as:

@Script("jquery-1.4.4.js")
@Script("jquery-1.4.4.min.js")

- OR -

Rather than having the Razor helpers at the bottom of the view page, you could move it to a separate file inside app_code. For that we need to do the below changes

1. Add the app_code folder in the solution if not available
2. Inside the folder create a MVC View Page(Razor). The page I created in my example is Content.cshtml
3. Delete all mark-up available in the page and move the helper script into the page

So the below code goes to the newly created view. You need to have the using directive 

@using System.Web.Mvc;

@helper Script(string scriptName, UrlHelper url)
{
    <script src="@url.Content("~/Scripts/" + scriptName)" type="text/javascript"></script>
}

4. In the view file (Eg: _Layout.cshtml)  refer the helper  as:

   @Content.Script("jquery-1.4.4.js", Url)
   @Content.Script("jquery-1.4.4.min.js", Url)





Monday, January 11, 2016

Display Annotations - ASP.NET MVC

ASP.NET MVC display annotations are pretty strait forward. Let's go for an example strait away.
I have an Employee class

        [Required]
        public virtual string Name { get; set; }

        public virtual string Address { get; set; }

        [DisplayName("Date of birth")]
        [DataType(DataType.Date)]
        public virtual DateTime DateOfBirth { get; set; }

        [Range(1, 5)]
        public virtual int Tier { get; set; }

        [DataType(DataType.Password)]
        public virtual string Password { get; set; }

        [DataType(DataType.MultilineText)]
        public virtual string Comments { get; set; }

        [DisplayName("Start date")]
        [DataType(DataType.Date)]
        public virtual DateTime StartDate { get; set; }

Output:


Friday, January 8, 2016

Create Custom Validator - ASP.NET MVC

In this example I am using a sample class called Employee class. I do a custom validation for the field "Date of birth". The Employee class looks something like below. Notice that the class inherits the IValidatableObject interface in order to implement the custom validation. Afterwards the Validate() method is implemented.

    public class Employee : IValidatableObject
    {
        public virtual int ID { get; set; }

        [Required]
        public virtual string Name { get; set; }
        public virtual string Address { get; set; }
        public virtual DateTime DateOfBirth { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var field = new[] { "DateOfBirth" };
            if (DateOfBirth > DateTime.Now)
            {
                yield return new ValidationResult("Invalid date of birth", field);
            }
        }
    }

If you don't use a second parameter when instantiating the ValidationResult object, then the validation message would show up on the top of the form in the Validation summary section

Result


Thursday, January 7, 2016

Create Custom Helpers - ASP.NET MVC

1) Create extension method

Here inside my helper class I did the following coding

using System.Web.Mvc;
...
...
public static class MyHelpers
    {
        public static MvcHtmlString Image(this HtmlHelper helper, string src, string alterText)
        {
            var builder = new TagBuilder("img");
            builder.MergeAttribute("src", src);
            builder.MergeAttribute("alt", alterText);
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
    }

2) Add the using directive in the View

The helper class resides within the "MvcBookReview.Infrastructure" namespace. Hence:

@using MvcBookReview.Infrastructure


3) Call the custom helper in view

<div>
    @Html.Image(@Model.ImageUrl, @Model.AlternateText)
</div>

Result:





Wednesday, January 6, 2016

HTML5 - Drawing 2D on Canvas

Rectangle
fillRect(x coordinate, y coordinate, width, height)

Round
arc(x coordinate, y coordinate, start angle, end angle, clockwise-or-counter-clockwise)

Linear Gradient
createLinearGradient(Start point - x coordinate, Start point - y coordinate, End point - x coordinate, End point - y coordinate)

Draw Text
fillText("The actualk text goes here", Start point - x coordinate, Start point - y coordinate)

Quadratic Bézier Curve
moveTo(Start point - x coordinate, Start point - y coordinate); //specify the start point
ctx.quadraticCurveTo(Bézier control point - x coordinate, Bézier control point - y coordinate,  End point - x coordinate, End point - y coordinate);

Example

<html>
<body>

<canvas id="myCanvas" width="400" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
//1 Capture the canvas
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

//2 Create gradient
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"blue");
grd.addColorStop(1,"black");

//3 Fill gradient
ctx.fillStyle = grd;
ctx.fillRect(10,200,150,80);


//4 Draw text inside the callout
var ctx = c.getContext("2d");
ctx.font = "17px Arial";
ctx.fillText("Hello World",32,70);

//5 Arc
ctx.arc(200, 400, 50, 0, 2 * Math.PI, false);
ctx.fillStyle = '#00994c';
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = '#003300';
ctx.stroke();

//6 Quadratic Bézier Curve
ctx.moveTo(75,25);
ctx.quadraticCurveTo(25,25,25,62.5);
ctx.quadraticCurveTo(25,100,50,100);
ctx.quadraticCurveTo(50,120,30,125);
ctx.quadraticCurveTo(60,120,65,100);
ctx.quadraticCurveTo(125,100,125,62.5);
ctx.quadraticCurveTo(125,25,75,25);
ctx.stroke();

</script>
</body>
</html>

Result