Saturday, 26 September 2015

Display and edit templated helpers in asp.net mvc

In this tutorial we will discuss about Template helper in asp.net mvc. Template helper is introduced in MVC-2, and it is classified into two categories.
1.   Display template
2.   Editor Template
Display Template Helper Type :-
1.   @Html.DisplayForModel() :- This Display template helper is used with strongly  typed views. It goes through the every property in the model for displaying object.
2.   @Html.DisplayFor(modal => modal) :- This Display template helper is used with strongly  typed views , if model has properties which return complex objects then this template helper is very useful.
3.   @Html.Display(“StudentData”) :- This Display template helper is not a strongly typed view. If we store data in viewData then this template helper is used to get that data by key.

Editor Template Helper Type :-
Like Display template Editor template also has 3 types
@Html.EditorForModel()
@Html.Editor("StudentData")
@Html.EditorFor(model => model)
These helper also work like display template.
1.    @Html.DisplayForModel() And  @Html.EditorForModel()

For  understanding this template we will take previous example class which we have designed like following. Previous example link is
[MetadataType(typeof(StudentMetaData))]
    public partial class Student
    {
    }

    public class StudentMetaData
    {
        #region dataType attribute

        [HiddenInput(DisplayValue = false)]
        public int Id { get; set; }

        [ReadOnly(true)]
        [DataType(DataType.EmailAddress)]
        public string EmailAddress { get; set; }


        [DataType(DataType.Currency)]
        public int? WinningPrize { get; set; }

        // Generate a hyperlink
        [DataType(DataType.Url)]
        [UIHint("OpenInNewWindow")]
        public string PersonalWebSite { get; set; }


        [DataType(DataType.Date)]
        public DateTime? AdmissionDate { get; set; }

    [DisplayAttribute(Name = "Full Name")]
    
public string FullName { get; set; }

    [
DisplayFormat(DataFormatString = "{0:d}")]
    
public DateTime? HireDate { get; set; }

    [
DisplayFormat(NullDisplayText = "Gender not specified")]
    
public string Gender { get; set; }
        #endregion
}


Now create a Home Controller and create Action method for Detail and Edit, we are taking previous example there we have already designed these action method.  
The Detail action method code is like following
   public ActionResult Details(int id)
        {
            MVCVariousAttributeEntities _context = new  MVCVariousAttributeEntities();
           Student _studentDetail =  _context.Students.Where(c => c.Id == id).SingleOrDefault();
           return View(_studentDetail);
        }


Create a view for Detail Action method with the strongly typed view and Scaffold template as “Detail”.
 When you  add this view then you will see lot of HTML code in this DetailView like following.
@model MVCApplicationWithVariousAttribute.Models.Student

@{
    ViewBag.Title = "Details";
}

<div style = "font-family:Arial">
<h2>Details</h2>
<fieldset>
    <legend>Student</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.FullName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.FullName)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Gender)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Gender)
    </div>

   

    <div class="display-label">
         @Html.DisplayNameFor(model => model.EmailAddress)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.EmailAddress)
    </div>


    <div class="display-label">
         @Html.DisplayNameFor(model => model.PersonalWebSite)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.PersonalWebSite)
    </div>
</fieldset>
</div>



 Instead of this we can use one the Display template so the view code will be like
@model MVCApplicationWithVariousAttribute.Models.Student

@{
    ViewBag.Title = "Details";
}

<div style = "font-family:Arial">
<h2>Details</h2>
@Html.DisplayForModel()


For the edit action method we can do same
@model MVCApplicationWithVariousAttribute.Models.Student

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<div style="font-family" Arial>
@using (@Html.BeginForm())
{
    @Html.EditorForModel()
}

</div>



2.    @Html.Display(“StudentData”) And @Html.Editor(“StudentData”)

This template is used when do not use scaffold template and we pass data through ViewData or ViewBeg.
Code for Edit Action method will be like following
    public ActionResult Details(int id)
        {
            MVCVariousAttributeEntities _context = new MVCVariousAttributeEntities();
           Student _studentDetail =  _context.Students.Where(c => c.Id == id).SingleOrDefault();
           ViewData["StudentData"] = _studentDetail;
           return View();
           return View(_studentDetail);
        }


And the view code will be like following
@{
    ViewBag.Title = 
"Details";
}

<h2>Details</h2>

<fieldset>
    
<legend>Student</legend>
    @Html.Display(
"StudentData")
</fieldset>

Same we can do with Edit template also

So when we run this application in all the condition output will be the same
For the display template output will be
The edit template will be






Hiddeninput and readonly attributes in asp.net mvc

In this tutorial we will discuss about HiddenInput and ReadOnly Attribute in asp.net MVC.
Hidden Input Attribute
Basically HiddenInput Attribute is used when we want to render a application property using InputType = Hidden. This is mostly used when we want that user is not able to see or edit the property, for this we need to post this property to the server when we submit this form.
This HiddenInput  Attribute is present in System.Web.Mvc namespace. 
Before proceeding this tutorial first go through to this tutorial  Link we learn Various Type of attribute in asp.net mvc .
Step(1):-  In previous tutorial we create a partial class of student.edmx we will take that student.cs class and we will make changes in that class means there we added a ID property which is decorated with HiddenInput attribute.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace MVCApplicationWithVariousAttribute.Models
{
    [MetadataType(typeof(StudentMetaData))]
    public partial class Student
    {
    }

public class StudentMetaData
{
 // Id property is hidden and cannot be changed
    [
HiddenInput(DisplayValue=false)]
    
public int Id { get; set; }

    
// Display mail to hyperlink
    [
DataType(DataType.EmailAddress)]
    
public string EmailAddress { get; set; }

    
// Display currency symbol. For country specific currency, set 
    // culture using globalization element in web.config. 

    // For Great Britain Pound symbol
    // <globalization culture="en-gb"/>
    [
DataType(DataType.Currency)]
    
public int? WinningPrize{ get; set; }

    // Generate a hyperlink
    [
DataType(DataType.Url)]
    
public string PersonalWebSite { get; set; }

    
// Display only Time Part
    // [DataType(DataType.Time)]


    // Display only Date Part
    [
DataType(DataType.Date)]
    
public DateTime? AdmissionDate { get; set; }
}
}

Here if we decorate this ID property with “HiddenInput” only like following that time it will not hide this property for that we have to add   [HiddenInput(DisplayValue=false)]
  //This will not hide property
[HiddenInput] 
    
public int Id { get; set; }


  [HiddenInput(DisplayValue=false)]
    
public int Id { get; set; }

Now run your application and render to this following link you will see that you will not see the ID property in this page 
http://localhost/MVCApplicationWithVariousAttribute/Home/Details/1

Step(2):- Now if we able to edit these property so for that go to the home controller and there we have “EDIT Action method” there we are passing ID of student and write the following code for the edit properties
   public ActionResult Edit(int id)
        {
            MVCVariousAttributeEntities _context = new MVCVariousAttributeEntities();
            Student _studentDetail = _context.Students.Where(c => c.Id ==        id).SingleOrDefault();
            return View(_studentDetail);
           // return View();
        }


This is the controller ,now we need the View for that right click on this action method and create a view with the name is EDIT.


and click on Add ,it will create a view . this edit view code will be like following
@model MVCApplicationWithVariousAttribute.Models.Student

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<div style="font-family" Arial>
@using (@Html.BeginForm())
{
    @Html.EditorForModel()
    <br />
    <br />
    <input type = "submit" value = "SaveRecord" />
}

</div>


Now run your application and navigate to the following link

http://localhost/MVCApplicationWithVariousAttribute/Home/Edit/1



Here if see the student full detail from here if go to page source we see that we have input element name is ID and Type is Hidden and the value is 1 so when we click on Save record button then this ID is save to server means this information will save in respective ID , so we can use this id to update the records.
ReadOnly Attribute :-
Readonly attribute is present in System.ComponentModel namespace. This property make sure that it make property Read only. Still we can make change in property but once we will post this form Model Binder will care of ReadOnly Attribute, means when we will post this form to server this will send this property as null and will not make any changes in this property. We can make property of a classbt removing SET accessor.
For example suppose we want make readonly EmailId so add a readOnly attribute to this property in student.cs class.
[MetadataType(typeof(StudentMetaData))]
    public partial class Student
    {
    }

    public class StudentMetaData
    {
        #region dataType attribute

        [HiddenInput(DisplayValue = false)]
        public int Id { get; set; }

        [ReadOnly(true)]
        [DataType(DataType.EmailAddress)]
        public string EmailAddress { get; set; }


        [DataType(DataType.Currency)]
        public int? WinningPrize { get; set; }

        // Generate a hyperlink
        [DataType(DataType.Url)]
        [UIHint("OpenInNewWindow")]
        public string PersonalWebSite { get; set; }


        [DataType(DataType.Date)]
        public DateTime? AdmissionDate { get; set; }

}
}


Now Go to the home controller and write the following code to the  POST Edit Action method .
[HttpPost]
        public ActionResult Edit(Student student)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    MVCVariousAttributeEntities _context = new MVCVariousAttributeEntities();
                    Student studentFromDB = _context.Students.Single(x => x.Id == student.Id);

                    // Populate all the properties except EmailAddrees
                    studentFromDB.FullName = student.FullName;
                    studentFromDB.Gender = student.Gender;
                    studentFromDB.Age = student.Age;
                    studentFromDB.PersonalWebSite = student.PersonalWebSite;

                    _context.ObjectStateManager.ChangeObjectState(studentFromDB, System.Data.EntityState.Modified);
                    _context.SaveChanges();
                    return RedirectToAction("Details", new { id = student.Id });
                }
                return View(student);
            }
            catch
            {
                return View();
            }
        }


 Now run your application and navigate to the following link

http://localhost/MVCApplicationWithVariousAttribute/Home/Edit/1

Modify every property here and click on Save Record you will see that all property changed except Email Id.



C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...