Monday, November 10, 2014

Custom Validation Attribute in ASP.Net MVC 4

Custom Validation Attribute in ASP.Net MVC 4

In this blog, I’m explaining how to create the custom validation attribute in asp.net mcv 4 and how to use it in our application.

Step 1

First create an empty asp.net mvc 4 application and add a model class named “Person” in it:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace CustomValidationMvcApp.Models
{
    public class Person
    {
        public int Id { get; set; }

        [Required(ErrorMessage="Name is madatory")]
        public string Name { get; set; }

        [Required(ErrorMessage="Date Of Birth is mandatoy")]
        [AgeComparison]
        [Display(Name="Date Of Birth")]
        public DateTime DOB { get; set; }
    }
}


Step 2

Now create another class named “AgeComparison” and this class will have the business logic of our custom attribute AgeComparison:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace CustomValidationMvcApp.Models
{
    public class AgeComparison : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            DateTime date = Convert.ToDateTime(value);
            long ticks = DateTime.Now.Ticks - date.Ticks;
            DateTime dtAge = new DateTime(ticks);

            if (dtAge.Year <= 18)
            {
                return new ValidationResult("You are not eligible for vote");
            }
            else{
                return new ValidationResult("You are eligible for vote");
            }
        }
    }
}
This custom attribute will tell you that you are eligible for vote or not by comparing your date of birth.


Step 3

Now add a controller to the project named “HomeController” and write the below code in it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CustomValidationMvcApp.Models;

namespace CustomValidationMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

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

        [HttpPost]
        public ActionResult Index(Person model)
        {
            return View();
        }

    }
}

Step 4

Now add a view named “Index” and write the below code in it:
@model CustomValidationMvcApp.Models.Person

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div style="margin: 0 auto; width:600px;">
        @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        {
            <div style="margin-top:10px;">
                <div style="width:100px;display:inline-block">
                    @Html.LabelFor(x => x.Name)
                </div>
                <div style="width:200px;display:inline">
                    @Html.TextBoxFor(x => x.Name)
                </div>
                <div style="width:200px;display:inline">
                    @Html.ValidationMessageFor(x => x.Name)
                </div>
            </div>
            <div style="margin-top:10px;">
                <div style="width:100px;display:inline-block">
                    @Html.LabelFor(x => x.DOB)
                </div>
                <div style="width:200px;display:inline">
                    @Html.TextBoxFor(x => x.DOB)
                </div>
                <div style="width:200px;display:inline">
                    @Html.ValidationMessageFor(x => x.DOB)
                </div>
            </div>
            <div style="margin-top:10px;">
                <div>
                </div>
                <div >
                    <input type="submit" value="Submit"/>
                </div>
            </div>
        }
    </div>
</body>
</html>



Your solution explorer will look like this:




OutPut

Now run the application:











Saturday, September 27, 2014

Reading data from Xml using Class Library in Asp.Net Mvc 4

Reading data from Xml using Class Library in Asp.Net Mvc 4

In this blog, I’m explaining how to read data from xml file using class library in asp.net mvc 4.


Step 1

First create a basic asp.net mvc 4 application and add a xml file named it “ProductXml” in the App_Data folder like this:







When you add ProductXml file then it will blank like this:




Step 2

Now add data in the xml file like this:




Below is my xml file:
<?xml version="1.0" encoding="utf-8" ?>
<Products>
  <Product>
    <ProductId>1</ProductId>
    <ProductName>Dell Inspiron</ProductName>
    <ProductCategory>Hardware</ProductCategory>
    <ProductCost>250</ProductCost>
  </Product>
  <Product>
    <ProductId>2</ProductId>
    <ProductName>Microsoft Office</ProductName>
    <ProductCategory>Software</ProductCategory>
    <ProductCost>100</ProductCost>
  </Product>
  <Product>
    <ProductId>3</ProductId>
    <ProductName>HP Pavilion</ProductName>
    <ProductCategory>Hardware</ProductCategory>
    <ProductCost>200</ProductCost>
  </Product>
  <Product>
    <ProductId>4</ProductId>
    <ProductName>Visual Studio 2012</ProductName>
    <ProductCategory>Software</ProductCategory>
    <ProductCost>300</ProductCost>
  </Product>
  <Product>
    <ProductId>5</ProductId>
    <ProductName>Microsoft SQL Server</ProductName>
    <ProductCategory>Software</ProductCategory>
    <ProductCost>100</ProductCost>
  </Product>
</Products>

Step 3

Now add another project to the solution and type of Class Library like this:







And name this class library XML.Helper


And add reference of System.Web  to the XML.Helper class library like this:






Step 4

Now add two classes to the XML.helper class library named “Products” and “XmlReader” like this:


Products


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace XML.Helper
{
    [Serializable]
    [XmlRoot("Products"), XmlType("Products")]
    public class Products
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public string ProductCategory { get; set; }
        public string ProductCost { get; set; }
    }
}


XmlReader


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace XML.Helper
{
    public class XmlReader
    {
        public List<Products> RetrunListOfProducts()
        {
            string xmlData = HttpContext.Current.Server.MapPath("~/App_Data/ProductsXml.xml");//Path of the xml script 
            DataSet ds = new DataSet();//Using dataset to read xml file 
            ds.ReadXml(xmlData);
            var products = new List<Products>();
            products = (from rows in ds.Tables[0].AsEnumerable()
                        select new Products
                        {
                            ProductId = Convert.ToInt32(rows[0].ToString()), //Convert row to int 
                            ProductName = rows[1].ToString(),
                            ProductCategory = rows[2].ToString(),
                            ProductCost = rows[3].ToString(),
                        }).ToList();
            return products;
        } 
    }
}


Step 5

Now add reference of the XML.Helper class library to the project like this:








Step 6

Now add controller to the project and named it “HomeController” like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XML.Helper;

namespace ClassLibraryMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            XmlReader readXML = new XmlReader();
            var data = readXML.RetrunListOfProducts();
            return View(data.ToList());
        }

    }
}

Step 7

Now add a view named “Index” to the project like this:

@model IEnumerable<XML.Helper.Products>

@{
    ViewBag.Title = "Index";
}

<h2>Product List using XML & Class Library in Asp.Net Mvc 4</h2>
<table class="table table-bordered">
    <tr>
        <th>Id</th>
        <th>Product Name</th>
        <th>Product Category</th>
        <th>Product Cost</th>
    </tr>
    @foreach (var item in Model)
    { 
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ProductId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ProductName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ProductCategory)
            </td>
            <td>
                $@Html.DisplayFor(modelItem => item.ProductCost)
            </td>
        </tr> 
    }
</table>

After doing all the above things, your solution explorer will look like this:





Output

Now run the application:






Your data has been populated from the xml file using the class library XML.Helper.

Thank you for reading my blog, you give your valuable comments and suggestion in the comment box.