Scaffolding in ASP.NET MVC 4.0

Scaffolding is one of the nice feature in ASP.NET MVC. The main purpose of scaffolding is it creates a starting point of code for you. Whatever application you are developing, you need to create Controller, Action Methods, Views and probably a database connection. Without scaffolding you need to do almost similar kind of job every time. It actually save some of your time by creating the basic code structure for you, on which you can start your work. You can change the scaffolding code to meet your exact requirement. Keep in mind that scaffolding code is not the final application code. It is just a starting point from you need to continue. If you are not happy with the way scaffolding works. You can change it. You can configure it to create basic starting code structure of your choice.

Continue reading “Scaffolding in ASP.NET MVC 4.0”

Download data as .CSV format from ASP.NET web application

CSV file is a comma separated file format. That means all the values in the file is comma separated. This is very simple and useful format to exchange data. You can create and read CSV very easily. It is in human readable as well as you can write your program logic to work with this format very easily. You need to place comma after every value in a line and at the time of reading also keep in mind. Many popular software and service also support CSV format. For example Microsoft Outlook, Gmail etc. Keep in mind that it is not hierarchical data rather it is tabular format which we can express in CSV format.

Continue reading “Download data as .CSV format from ASP.NET web application”

Model validation in ASP.NET MVC 2.0

Input validation is an important topic in software applications. We should always validate the inputs which are coming through for example input form elements. When we are working with Web Form then we can use the various validator controls for validations. Validation controls can do most of the hard working for a developer. In this post our main discussion is input validation in ASP.NET MVC 2.0

Server side validation

Input validation can be done in two places. One is at the server side and another is at the client side. Server side validation is the actual validation and we should always do that. We should not only depend on the client validation, because client validation is done at browser using some client side scripting like JavaScript. One can easily turn off JavaScript in browser and can able to push invalid data to our application. Server side validation is the safe guard of this kind of problems. If our validation logic has some business rule then we should do that only in server side, because any one can easily see the client side JavaScript code.

Client side validation

On the other hand client side validation is for performance. Because to execute server side validation every time the form needs to be submitted. If we do client side validation then before submitting the form to server our input data can be validated. The user can get a better experience with our application.

Both side

So the summary is we should do input validation at both side. Client side is for performance and server side is for the actual validation and the safe guard. If the input data can or can not be validated at client side then server side always validate it. If some one intentionally disable JavaScript or using some old browser also can not push invalid data to our application because of the server side validation.

Validation with ASP.NET MVC

ASP.NET MVC is for better and maintainable patterns for projects. Here we should not put any logic in views. So how we can do input validation in ASP.NET MVC? The answer is we should do input validation at models. Models can be use in various views and controller in MVC. If we do our validation at model level then it will be DRY (don’t repeat yourself) enough to maintain. Also you can use a view specific model for this job.

ASP.NET MVC also provide some functionality using them we can declaratively implement our validation logic which are so common like required field, compare field, regular expression etc. We can also do our custom validation logic by extending the framework’s existing logic.

Here a short example of the model class with various input validation logic in place with declarative approach.

Model

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace ModelValidation.Models
{
    public class Registration
    {
        [Required(ErrorMessage = "Please enter name.")]
        [StringLength(20, ErrorMessage = "Name must be 20 char max.")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please enter phone number.")]
        [StringLength(10, ErrorMessage = "Phone number must be 10 digit max.")]
        [Display(Name = "Phone Number")]
        public long PhoneNumber { get; set; }

        [Required(ErrorMessage = "Please enter email.")]
        [StringLength(20, ErrorMessage = "Email must be 20 char max.")]
        [DataType(DataType.EmailAddress)]
        [RegularExpression(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", ErrorMessage = "Please enter valid email id.")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Please enter user name.")]
        [StringLength(20, ErrorMessage = "User name must be 20 char max.")]
        [Display(Name = "User Name")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Please enter password.")]
        [StringLength(20, MinimumLength = 6, ErrorMessage = "Password name must be in between 6 to 20 char.")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Compare("Password", ErrorMessage = "Password and confirm pssword must match")]
        [Display(Name = "Confirm Password")]
        [DataType(DataType.Password)]
        public string ConfirmPassword { get; set; }

        public Address AddressDetails { get; set; }
    }

    public class Address
    {
        [Required(ErrorMessage = "Please enter Street name.")]
        [StringLength(20, ErrorMessage = "Streen name must be 20 char max.")]
        [Display(Name = "Street Name")]
        public string StreetName { get; set; }

        [Required(ErrorMessage = "Please enter state.")]
        [StringLength(20, ErrorMessage = "State must be 20 char max.")]
        public string State { get; set; }

        [Required(ErrorMessage = "Please enter country.")]
        [StringLength(20, ErrorMessage = "Country must be 20 char max.")]
        public string Country { get; set; }
    }
}

Repository

public interface IRegistrationRepositary
{
    void Register(Registration reg);
}

public class RegistrationRepositary : IRegistrationRepositary
{
    public void Register(Registration reg)
    {
        // Save new Registration to DB here...
    }
}

Controller

using System.Web.Mvc;
using ModelValidation.Models;

namespace ModelValidation.Controllers
{
    public class RegistrationController : Controller
    {
        public IRegistrationRepositary RegisterRepo { get; set; }

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            if (RegisterRepo == null)
            {
                RegisterRepo = new RegistrationRepositary();
            }
            base.Initialize(requestContext);
        } 

        //
        // GET: /Registration/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Registration/Create

        [HttpPost]
        public ActionResult Create(Registration reg)
        {
            try
            {
                // Cleck model state valid or not.
                if (ModelState.IsValid) 
                {
                    // Call the repositary to save the data.
                    RegisterRepo.Register(reg); 
                }
                else
                {
                    return View();
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

So we can see here that validating the model state is easy at our controller level.

// Cleck model state valid or not.
if (ModelState.IsValid) 
{
    RegisterRepo.Register(reg);
}

This will enable our server side input validation. For client side validation we simply needs to activate it at view level. The same logic will be implemented at client side using JavaScript.

<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>

<% Html.EnableClientValidation(); %> 

If you are using any object relational model which generated model class with designer tool like Entity Framework database first or model first approach then you can do the following procedure for model validation.

Suppose we have a model class ‘Employee’ which is generated by Entity Framework designer tool.

using System.ComponentModel.DataAnnotations;

namespace ModelValidation.Models
{
    [MetadataType(typeof(EmployeeValidation))]
    public partial class Employee
    {
    }

    public class EmployeeValidation
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "Please enter name.")]
        [StringLength(10)]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please enter department.")]
        [StringLength(10)]
        public string Department { get; set; }
    }
}

Now it will be validated with same approach.

Basic Introduction of ASP.NET MVC

MVC is a fresh experience for the Microsoft ASP.NET developer. Last one year I am working with this framework. The most important thing is that ASP.NET MVC build on top of .NET Framework and can take advantage of the exiting .NET features like CLR, BCL, JIT etc. For one who is using ASP.NET Web Form it will be a good fresh experience like me.

What is ASP.NET MVC?

It is always good practice to build application which have different layers and they have less strong dependencies between them. By doing so we can gain some advantages like parallel development, maintainable code, testable code etc. When we are using ASP.NET Web Form then it can not be fully possible, because Web Form having tight relation between presentation layer and application logic by code behind files. We can not test the presentation layer easily because it has tight relation with ASP.NET runtime. The code behind files always hold the application logic and we can not easily decouple it with the aspx page.

On the other hand MVC has three layer with the name Model, View and Controller. Model means the domain objects of our application. View means the pure presentation layer with out any application logic (we should not write any logic here) and the Controller means the application logic of our application. So here the Controller is responsible to populate the model with data and call the view to create the presentation. By using this three layer you can divide the responsibilities. MVC has the option to heavy use of interfaces and dependency injection, so that we can test every layers of the application (also we should create a wrapper for the static classes for testability). We can test the Controller with out any dependencies with the ASP.NET runtime.

ASP.NET MVC is light weight. Almost every component is pluggable here. Like you can use a different view engine or a different validation framework in ASP.NET MVC. Microsoft also implement it as a convention over configuration in mind. That means many things are done simply following the convention, you do not have to be configure it explicitly. For example views are kept on particular folders with the same name of the controller and the controller can find them with out any more coding from the developer’s end. I think the most exiting feature of ASP.NET MVC is model binding. You can create a view specific model and can create a strongly typed view with that model. It will actually render and populate the model object for you. Another fine feature is attribute based model validation in ASP.NET MVC. We can declare attribute for our validation on model properties. By which our validation logic will be DRY (don’t repeat yourself) enough so that where we are using that model our validation will be in one place, easy to maintain. You can also extends validation logic in ASP.NET MVC.

MVC
MVC

Basic demo

Here a small and very basic sample of ASP.NET MVC:

Model:

using System.Collections.Generic;

namespace MvcApplication4.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }

    public class EmployeeDB
    {
        public List<Employee> GetAll()
        {
            // In real application data may be coming from database.
            return new List<Employee>()
            {
                new Employee(){ Id = 1, Name = "Rahul", Department = "Software" },
                new Employee(){ Id = 2, Name = "Mita", Department = "HR" },
                new Employee(){ Id = 3, Name = "Bob", Department = "Sales" },
            };
        }
    }
}

Controller:

using System.Collections.Generic;
using System.Web.Mvc;
using MvcApplication4.Models;

namespace MvcApplication4.Controllers
{
    public class EmployeeController : Controller
    {
        //
        // GET: /Employee/

        public ActionResult Index()
        {
            EmployeeDB empDB = new EmployeeDB();
            IList<Employee> emps = empDB.GetAll(); // Get the data.
            return View(emps); // Return view with model data.
        }
    }
}

View:

<%@ Page 
    Title="" 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication4.Models.Employee>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Index</h2>

    <table>
        <tr>
            <th></th>
            <th>Id</th>
            <th>Name</th>
            <th>Department</th>
        </tr>
    <% foreach (var item in Model) 
       { %>
        <tr>
            <td>
                <%: Html.ActionLink("Edit", "Edit", new { id = item.Id }) %> |
                <%: Html.ActionLink("Details", "Details", new { id = item.Id })%> |
                <%: Html.ActionLink("Delete", "Delete", new { id = item.Id })%>
            </td>
            <td><%: item.Id %></td>
            <td><%: item.Name %></td>
            <td><%: item.Department %></td>
        </tr>
    <% } %>
    </table>

    <p><%: Html.ActionLink("Create New", "Create") %></p>

</asp:Content>

For more information on ASP.NET MVC please take a look here

jQuery UI dialog

A dialog is a floating window that contains a title bar and a content area. The dialog window can be moved, resized and closed with the ‘x’ icon by default.

by jQuery UI

I blogged about showing popup for user confirmation before doing something permanently in our application. This is a rule of thumb when design software. I created a small demo as an example to show how we can show a confirm box before delete record from persistent layer for example database. In that example I used a plain JavaScript confirm box for user confirmation. It may be enough for our simple and in house applications. But for internet based public application we need a more sophisticated solution over a simple JavaScript confirmation box. For that kind of applications we need more beautiful user interface.

We have some options for this problem. We can design a ‘div’ element and design it as an popup and using some JavaScript we can show it when we want the confirmation. But today I am using a library which is from jQuery for my solution. This is jQuery UI plugin. This library has a dependency on jQuery core. That means we need the jQuery core library in our page when we are using this plugin. This plugin has a function called ‘dialog()’ using this function we can popup a simple ‘div’ element as popup. To make things simple I am going to show a simple code.

If we want to show a simple dialog using this plugin then we can use this code.

<!-- CSS for jQuery UI. -->
<link href="../../Content/jquery-ui.min.css" rel="stylesheet" type="text/css" />

<!-- jQuery core library. -->
<script src="../../Scripts/jquery-1.8.3.js" type="text/javascript"></script>   

<!-- jQuery UI plugin. -->
<script src="../../Scripts/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function () {
    $("#dialog").dialog(); // Show 'div' as a dialog.
});
</script>

<div id="dialog" title="Demo Dialog">
    This is my dialog box.
</div>

This will show the div as a dialog. The title of the ‘div’ will be the title of the dialog. So simple. If we want to show a ‘OK’ button inside our dialog then we can use this code.

$("#dialog").dialog({
    buttons: {
        OK: function () {
            $(this).dialog("close");
        }
    }
});

Dialog function can accept object literal. Through that we can set many option of our dialog. Also this plugin have some theme to select. You can also create your own theme to use. Depending on your theme the CSS can be downloaded. I am here using the most basic theme. In real applications we should use theme which will match our application look and feel, if not then we should create one. For full documentation please take a look at jQuery UI plugin.

Lets go to my main code. I am going to use this plugin to convert my plain confirm box with a more beautiful dialog box in my demo example. First of all I am creating a ‘div’ element as my dialog.

<div id="dialog" title="Delete Confirmation">
    Are you sure?
</div>

Next in the place where I wrote the code to show a plain JavaScript dialog box, I am going to replace that code to this.

// Show confirmation dialog and pass the 'event' paramer
// to use the object inside the function for which the 
// 'click' event fired, in this case the perticular 'delete' link.
$(".deleteLink").click(function (event) {
    $("#dialog").dialog({
        modal: true,
        buttons: {
            OK: function () {
                $(this).dialog("close");
                window.location = "http://<%: Request.Url.Host %>:<%: Request.Url.Port %>/Customer/Delete/" + 
                    event.target.id; // Get the ID of the record from the 'delete' link id.
            },
            Cancel: function () {
                $(this).dialog("close"); // Cancel the 'delete' operation.
            }
        }
    });
});

Also at place where the delete link was I am going to replace that code.

<a class="deleteLink" href="#" id="<%: item.CustomerID %>">Delete</a>

When the user click on the delete link then the dialog will come up for the confirmation. This confirmation have two buttons. One is ‘OK’ and another is ‘Cancel’. Clicking on the ‘Cancel’ button will close the dialog and do nothing. That means it will not continue with the deletion process. But when the ‘OK’ button is clicked the deletion process will continue. For that it will collect some information like host name, port number and the id of the record which will delete (the id of the record is actually the id of the delete link which is dynamically populated using my model object). Using these information dynamically the deletion link is created and call the deletion controller. The deletion controller will actually continue the process at the server side. For simplicity I am not discussing the deletion logic here. Also it is out of my present discussion.

So the full code will be following.

<%@ Page 
    Title="" 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Customer>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">  
  
    <link href="../../Content/jquery-ui.min.css" rel="stylesheet" type="text/css" />

    <script src="../../Scripts/jquery-1.8.3.js" type="text/javascript"></script>   
    <script src="../../Scripts/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>
    
    <script language="javascript" type="text/javascript">
        $("document").ready(function () {
            
            // Show confirmation dialog and pass the 'event' paramer
            // to use the object inside the function for which the 
            // 'click' event fired, in this case the perticular 'delete' link.
            $(".deleteLink").click(function (event) {
                $("#dialog").dialog({
                    modal: true,
                    buttons: {
                        OK: function () {
                            $(this).dialog("close");
                            window.location = "http://<%: Request.Url.Host %>:<%: Request.Url.Port %>/Customer/Delete/" + 
                                event.target.id; // Get the ID of the record from the 'delete' link id.
                        },
                        Cancel: function () {
                            $(this).dialog("close"); // Cancel the 'delete' operation.
                        }
                    }
                });
            });
        });
    </script>

    <h2>Index</h2>

    <table>
        <tr>
            <th></th>
            <th>CustomerID</th>
            <th>CompanyName</th>
            <th>ContactName</th>
            <th>ContactTitle</th>
            <th>Address</th>
            <th>City</th>
            <th>Region</th>
            <th>PostalCode</th>
            <th>Country</th>
            <th>Phone</th>
            <th>Fax</th>
        </tr>
        <% foreach (var item in Model)
            { %>
        <tr>
            <td>
                <%: Html.ActionLink("Edit", "Edit", new { id = item.CustomerID }) %> |
                <%: Html.ActionLink("Details", "Details", new { id = item.CustomerID })%> |

                <!-- Store the ID of the record for use at the time of deletion. -->
                <a class="deleteLink" href="#" id="<%: item.CustomerID %>">Delete</a>
            </td>
            <td><%: item.CustomerID %></td>
            <td><%: item.CompanyName %></td>
            <td><%: item.ContactName %></td>
            <td><%: item.ContactTitle %></td>
            <td><%: item.Address %></td>
            <td><%: item.City %></td>
            <td><%: item.Region %> </td>
            <td><%: item.PostalCode %></td>
            <td><%: item.Country %></td>
            <td><%: item.Phone %></td>
            <td><%: item.Fax %></td>
        </tr>
        <% } %>
    </table>

    <p><%: Html.ActionLink("Create New", "Create") %></p>

    <div id="dialog" title="Delete Confirmation">
        Are you sure?
    </div>
</asp:Content>
jQuery Dialog
jQuery Dialog

Happy coding.