Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Data Annotations

Data Annotations

 In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace and are available to Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms and also to Entity framework ORM models.

Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.
The idea behind using data annotations is to add constraints metadata to the properties in the view model. This metadata is then picked up by the default binder when

Data Annotation Validator Attributes

DataType – Specify the datatype of a property
DisplayName – specify the display name for a property.
DisplayFormat – specify the display format for a property like different format for Date property.

The data annotations are listed and described in detail:

1.   EmailAddress: Indicates that the value must be a well-formatted e-mail address.

2.  CreditCard :Defines the value as a credit card number (15 or 16 digits without spaces or dashes).

3.  Required: Specify a property as required.

4.   ReqularExpression  : Validate the value of a property by specified regular expression pattern.

5   Range: Validate the value of a property within a specified range of values.

6.   StringLength : Specify min and max length for a string property.

7.   MaxLength : Specify max length for a string property.

8 .  Bind – Specify fields to include or exclude when adding parameter or form values to model properties.

9.   ScaffoldColumn : Specify fields for hiding from editor forms.

10.  EnumDataType(typeof(name of enum)) :Enables a .NET Framework enumeration to be mapped to a data column.The value must be one of those defined in the enumeration.

11.  FileExtension(Extensions="") : Validates that the file extension of the uploaded file is in the acceptable extensions defined; for example, [FileExtensions(Extensions=".jpg,.png,.gif")].

 

Data annotation Example:

public class Company
    {
        [Key]
        public Int16 CmpId { get; set; }
 
        [Required(ErrorMessage = "Name is required")]
        [StringLength(150)]
        [RegularExpression("^[A-Za-z0-9][A-Za-z0-9_ .-]*", ErrorMessage = "Invalid company name")]
        public string CmpName { get; set; }
 
        [Required(ErrorMessage = "Regestration number is required")]
        [StringLength(150)]
        public string CmpRegestration { get; set; }
 
 
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        [Required(ErrorMessage = "Registration Date is required")]
        public DateTime CmpRegDate { get; set; }
 
        [Required(ErrorMessage = "Email is required")]
        [DataType(DataType.EmailAddress)]
        [StringLength(150)]
        [RegularExpression(@"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$")]
        public string CmpEmail { get; set; }
 
 
        public Guid CreatedBy { get; set; }
 
        [ForeignKey("CreatedBy")]
        public aspnet_Users User { get; set; }
 
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        public DateTime? CreatedDate { get; set; }
 
    }
 



 Custom Data Annotations:

You can create your own custom validations by creating custom data annotations.To create a custom annotation, you need to create a class that inherits from ValidationAttribute, and the name of that class must end with the suffix Attribute.

For example leave application has “from date” and “To date”, now you have to apply custom validation that to date should be always greater than from date.

Following example compares date, if to date is less than from Date then custom data annotation create error message.

Example:

#region Date compare Rule

    public sealed class IsDateAfter : ValidationAttribute
    {
        private readonly string testedPropertyName;
        private readonly bool allowEqualDates;
 
        public IsDateAfter(string testedPropertyName, bool allowEqualDates = false)
        {
            this.testedPropertyName = testedPropertyName;
            this.allowEqualDates = allowEqualDates;
        }
 
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var propertyTestedInfo = validationContext.ObjectType.GetProperty(this.testedPropertyName);
            if (propertyTestedInfo == null)
            {
                return new ValidationResult(string.Format("unknown property {0}", this.testedPropertyName));
            }
 
            var propertyTestedValue = propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);
 
            if (value == null || !(value is DateTime))
            {
                return ValidationResult.Success;
            }
 
            if (propertyTestedValue == null || !(propertyTestedValue is DateTime))
            {
                return ValidationResult.Success;
            }
 
            // Compare values
            if ((DateTime)value >= (DateTime)propertyTestedValue)
            {
                if (this.allowEqualDates)
                {
                    return ValidationResult.Success;
                }
                if ((DateTime)value > (DateTime)propertyTestedValue)
                {
                    return ValidationResult.Success;
                }
            }
 
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
 
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessageString,
                ValidationType = "isdateafter"
            };
            rule.ValidationParameters["propertytested"] = this.testedPropertyName;
            rule.ValidationParameters["allowequaldates"] = this.allowEqualDates;
            yield return rule;
        }
    }

    #endregion

 

Use of custom validation:

   public class Leave
    {
        [Key]
        public int LeaveId { get; set; }
 
        public BlogProj.Models.Enum.LeaveCatogry LeaveCatogry { get; set; }
 
        [Display(Name = "From")]
        public DateTime? FromDate { get; set; }
 
        [Display(Name = "To")]
        [IsDateAfter("FromDate", true,ErrorMessage="To date should be after from date")]
        public DateTime? ToDate { get; set; }
  }



ASP.NET MVC

What is MVC?

MVC stands for Model-View-Controller. It is a software architectural design pattern which was introduced in 1970s.

MVC separates the representation and the user interaction.

MVC is divided in to three sections:

View:  Responsible for look and feel.
Model: Represents the real world object and provides data to the “View”.
Controller:  Responsible to take the end user request and load the appropriate   “Model” and “View”.

Detailed Description:

Model – The Model represents a set of classes that describe the business logic i.e. business model as well as data access operations i.e. data model. It also defines business rules for data means how the data can be changed and manipulated.

View – The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the controller as the result. This also transforms the model(s) into UI.

Controller – The Controller is responsible to process incoming requests. It receives input from users via the View, then process the user’s data with the help of Model and passing the results back to the View. Typically, it acts as the coordinator between the View and the Model.

Example:

Model:

public class Company
    {
        [Key]
        public Int16 CmpId { get; set; }
 
        [Required(ErrorMessage = "Name is required")]
        [StringLength(150)]
        [RegularExpression("^[A-Za-z0-9][A-Za-z0-9_ .-]*", ErrorMessage = "Invalid company name")]
        public string CmpName { get; set; }
 
        [Required(ErrorMessage = "Regestration number is required")]
        [StringLength(150)]
        public string CmpRegestration { get; set; }
 
        [Required(ErrorMessage = "Key peoples required")]
        public string CmpKeypersons { get; set; }
 
        [StringLength(2000)]
        public string Description { get; set; }
 
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        [Required(ErrorMessage = "Registration Date is required")]
        public DateTime CmpRegDate { get; set; }
 
        [Required(ErrorMessage = "Email is required")]
        [DataType(DataType.EmailAddress)]
        public string CmpEmail { get; set; }
 
        public Guid CreatedBy { get; set; }
 
        [ForeignKey("CreatedBy")]
        public aspnet_Users User { get; set; }
 
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        public DateTime? CreatedDate { get; set; }
 
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        public DateTime UpdateDate { get; set; }
 
        public string UpdateBy { get; set; }
    }

View:

@model IEnumerable<BlogProj.Models.Company>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="../../MyScripts/jquery-ui.js" type="text/javascript"></script>
<link href="../../Content/themes/demos.css" rel="stylesheet" type="text/css" />
 
<div style="height:25px"></div>
  <fieldset class="ui-widget-content" style="text-align:center">
        <legend>  @Html.ActionLink("Create New", "Create")</legend>
 
        <div style="height:20px"></div>
<table class="ui-widget-content" style="border-spacing:0px" style="border-spacing:0px">
    <tr class="ui-widget-header">
    <th></th>
        <th>
            Id
        </th>
        <th>
           Name
        </th>
        <th>
            Reg Date
        </th>
         <th>
            RegestrationId
        </th>
         <th>
           Key Persons
        </th>
    
         <th>
           Created By 
        </th>
         <th>
         Created Date
        </th>
        <th>
         Actions
        </th>
    </tr>
 
@foreach (var item in Model)
{
    <tr>
    <td></td>
    <td>
            @Html.DisplayFor(modelItem => item.CmpId)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CmpName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CmpRegDate)
        </td>
       
          <td>
            @Html.DisplayFor(modelItem => item.CmpRegestration)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CmpKeypersons)
        </td>
          <td>
            @Html.DisplayFor(modelItem => item.User.UserName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CreatedDate)
        </td>
 
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.CmpId }) |
            @*@Html.ActionLink("Details", "Detail", new { id = item.CmpId }) |*@
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
   </tr>
   
}
</table>
</fieldset>

 

Controller:

 

Namespace CodeChef4uLeave.Controllers
{
    public class CompanyController : Controller
    {
        private UnituOfWork unitOfWork = new UnituOfWork();
        //
        // GET: /Leave/
 
        public ActionResult Index()
        {
            var Companies = unitOfWork.GetAllCompanies();
            return View(Companies);
       
        }
   }
}

Layout

Layout:

1.  Layout  are like master pages in ASP.NET Web form. Master pages give a standard look and feel for Web form views while layout gives standard look and feel or acts like a template for razor views.
2.  Layouts are used to maintain a consistent look and feel across multiple views within ASP.NET MVC application.

 In MVC application layout is created below shared folder, following image shows details


Example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
 
    <!--site design or layout css-->
   <link href="@Url.Content("~/Content/style.css")" rel="stylesheet" type="text/css" />
     
    <!--Jquery theme css-->
   <link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
 
    <!--menu css-->
    <link href="@Url.Content("~/Content/superfish.css")" rel="stylesheet" type="text/css" />
  
        <!--Default js-->
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
 
 
        <!--menu js-->
    <script src="@Url.Content("~/MyScripts/hoverIntent.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/MyScripts/superfish.js")" type="text/javascript"></script>
  
  
 <script type="text/javascript">
 
     //button
     $(function () {
         $("input[type=submit],a,button")
                                    .button()
                                    .click(function (event) {
                                        //                                 event.preventDefault();
                                    });
     });
 
     //corner all code
     $(function () {
         $('input').addClass("ui-corner-all");
     });
            </script>
 
</head>
<body>
<div class="main">
  <div class="header">
    <div class="header_resize">
      <div class="logo"><h1><span>Easy</span> Leave<small>HR For All</small></h1>
         
      </div>
     <!--menu code -->
      <div class="menu">
       <ul>
         <li><h3>About us</h3></li>
          <li><h3>Products</h3></li>
          <li><h3>Contact us</h3></li>    
          <li>
          </li>
          <li> <div id="logindisplay">
         @Html.Partial("_LogOnPartial") </div></li>
        </ul>
 
 
      </div>
      <div class="text_header">
     @if (Request.IsAuthenticated)
     {
        <nav>
<ul class="sf-menu" id="example">
                                      @if (User.IsInRole("Admin") || User.IsInRole("Superadmin"))
                    {
              
    <li class="current">
 
              
                                                <a href="#">Admin</a>
                <ul>
                <li>
                <a href="#">Employee</a>
                <ul>
                  
                     <li>@Html.ActionLink("Employee", "Index", "Employee")</li>
                                                    <li>@Html.ActionLink("Designation", "Index", "Designation")</li>
                    <li>@Html.ActionLink("Role", "Index", "Role")</li>
                   <li>@Html.ActionLink("Change Password", "ChangePassword", "Account")</li>
                
                    </ul>
                </li>
                <li>
                                                                        <a href="#">Company Masters</a>
                                                                        <ul>
         
                                                                                      <li>@Html.ActionLink("Company", "Index", "Company")</li>
                                                                                     <li>@Html.ActionLink("Department", "Index", "Department")</li>
         
                                                                        </ul>
                                       </li>
                                        </ul>
                </li>
       }
           <li class="current">
                                                <a href="#">Reports</a>
                                                <ul>
                                                <li>
                                                    @Html.ActionLink("Dash Board", "DashBoard", "Reports")
                                                </li>
                 </ul>
                                    </li>
                                    <li>
 
                <a href="#">Configuration</a>
                <ul>
                                    <li>
                                                                        @Html.ActionLink("Holiday List", "Index", "LeaveMaster")
                                                            </li>
                                                    <li>@Html.ActionLink("Comp Off", "Index", "CompOff")</li>
                                        </ul>
                                    </li>    
 
                        </ul>
        </nav>
     }
   <!--menu code ends here -->
      </div>
      <div class="clr">
              
           </div>
    </div>

    <div class="headert_text_resize_bg">
      <div class="headert_text_resize">  @RenderBody()
        <div class="textarea">
    
        </div>
      </div>
    </div>
    <div class="clr"></div>
  </div>
 
 
 
  <div class="body">
    <div class="body_resize">
    
   
      <div class="clr"></div>
    </div>
  </div>
    
  <div class="clr"></div>
  <div class="footer">
    <div class="footer_resize">
       <footer>
       © Copyright ,Pune 2015
        </footer>
 
    </div>
    <div class="clr"></div>
  </div>
</div>
</body>
</html>
 

 

Using Layout in view:

You can use a layout to define a common template for your site. A layout can be declared at the top of view as

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
  }

OR

While creating view select check box option “Use Layout or master page”

Select proper layout in URL or path section, following image explains in detail.