ASP.Net Web Services – Getting Started

In the past 10 months, we were discussing about ASP.Net MVC, Entity Framework, jQuery, LINQ and many more stuffs. Today, we are going to start with ASP.Net Web Services.

What are web services and why should we use them?

Web services are a standardized way for developing interoperable applications.  That is, enabling an application to invoke a method of another application. These applications can be on the same computer or on different computers. Web services use open standards and protocols like HTTPXML and SOAP. Since these are open and well known protocols, applications which are built on any platform can interoperate with web services. For example, a JAVA application can interoperate with a web service which is built using .NET. Similarly a web service which is built using JAVA can be consumed by a .NET application.

Hyper Text Transfer Protocol (HTTP) is the protocol which is widely used by web services to send and receive messages. The messaging protocol is SOAP. SOAP stands for Simple Object Access Protocol. SOAP messages are in XML format.

Let’s try to understand these with an example. To create a sample ASP.NET web service, follow the below steps.

Step 1Create a an ASP.NET Empty Web Application and name it as WebServicesDemo.

Step 2Right click on WebServicesDemo project in solution explorer and add New ItemFrom the Add New Item dialog box, select Web Service. Change the name from WebService1.asmx to CalculatorWebServices.asmx.

Asp.NetWebServices1

Asp.NetWebServices2

Notice that WebService is a class that is decorated with [WebService] attribute and inherits from System.Web.Services.WebService base class. The [WebService] attribute tells that this class contains the code for a Web Service. WebService Namespace is used to uniquely identify your web service on the internet from other services that are already there on the web. WebService Namespace can be any string, but it is common to give a company’s internet domain name as they are usually unique. For example, [WebService(Namespace"http:// BestTEchnologyblog.com/webservices")]

To allow a web service to be called from JavaScript using ASP.NET AJAX, decorate the WebService class with [System.Web.Script.Services.ScriptService] attribute.

Step 3Copy and paste the following code in CalculatorWebServices.asmx

using System.Web.Services;

namespace WebServicesDemo
{
    [WebService(Namespace = "http://BestTEchnologyblog.com/webservices")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class CalculatorWebServices : System.Web.Services.WebService
    {
        [WebMethod]
        public int Add(int firstNumber, int secondNumber)
        {
            return firstNumber + secondNumber;
        }
    }
}

Asp.NetWebServices3

Notice that the CalculatorWebServices class contains a single method called Add(). This method adds 2 numbers and returns the sum. This method is decorated with [WebMethod] attribute. If you want this method to be exposed as part of the web service, the method must be public and should be decorated with [WebMethod] attribute. This attribute has got several properties which can be used to configure the behavior of the XML web service method. We will discuss these properties in the later articles.

At this point, we have successfully created a Web Service. Build the solution and run the application. We should get a page like below.

Asp.NetWebServices4

We can see a link called Service Description on the upper right hand side of the page. If we click on the link, it takes us to WSDL page. WSDL stands for Web Service Description Language.

Asp.NetWebServices5

On the other hand, when we click on the Add method, it will take us to a page where we can test our web service method. Let’s pass firstNumber as 10 and secondNumber as 20 and click on the Invoke button.

Asp.NetWebServices6

We will get a result of 30.

Asp.NetWebServices7

So points here to ponder are following:

  • WebService is a class that is decorated with [WebService] attribute and inherits from System.Web.Services.WebService base class. The [WebService] attribute tells that this class contains the code for a web service.
  •  WebService Namespace is used to uniquely identify your web service on the internet from other services that are already there on the web. WebService Namespace is common to be given a company’s internet domain name as they are usually unique.
  • To allow a web service to be called from JavaScript using ASP.NET AJAX, decorate the WebService class with [System.Web.Script.Services.ScriptService] attribute.
  • If you want a method to be exposed as part of the web service, the method must be public and should be decorated with [WebMethod] attribute.

What’s next?

In the next article, we will discuss about Consuming a web Service from a client application.

Reference: Arun Ramachandran (http://BestTEchnologyBlog.Com)

SQL Server – How to write stored procedures with output parameters?

In last day, we were discussing about different kinds of Templated Helpers in ASP.Net MVC. You can read that article hereFor a change, I am switching over to SQL Server. Today, we will discuss about writing stored procedures with output parameters in SQL Server.

Let’s understand this with an example. In the example, we will be using tblEmployee table.

SQL1

To create a stored procedure with output parameter, we use the keywords OUT or OUTPUT. @EmployeeCount in the below stored procedure is an OUTPUT parameter. Notice that it is specified with OUTPUT keyword.

CREATE PROCEDURE spGetEmployeeCountByGender
@Gender nvarchar(20),
@EmployeeCount int Output
AS
BEGIN
SELECT @EmployeeCount = COUNT(Id)
FROM tblEmployee
WHERE Gender = @Gender
END

SQL2

To execute this stored procedure with OUTPUT parameter, follow the below steps.

  1. First initialise a variable of same datatype as that of the output parameter. Here we have declared @EmployeeTotal integer variable.
  2. Then pass the @EmployeeTotal variable to the stored procedure. You have to specify the OUTPUT keyword. If you don’t specify the OUTPUT keyword, the variable will be NULL.
  3. Then execute the stored procedure.

DECLARE @EmployeeTotal int

EXECUTE spGetEmployeeCountByGender ‘Female’, @EmployeeTotal output

PRINT @EmployeeTotal

SQL3

If you don’t specify the OUTPUT keyword, while executing the stored procedure, the @EmployeeTotal variable will be NULL. In the example below, we have not specified OUTPUT keyword. So while executing the stored procedure, a message of @EmployeeTotal is null is printed.

DECLARE @EmployeeTotal int

EXECUTE spGetEmployeeCountByGender ‘Female’, @EmployeeTotal

IF(@EmployeeTotal is null)
PRINT ‘@EmployeeTotal is null’
ELSE
PRINT ‘@EmployeeTotal is not null’

SQL4

While using the parameter names,  you can pass the parameters in any order. In the example below, we are first passing the OUTPUT parameter and then the input @Gender parameter. But we will get the total number of male employees without any errors.

DECLARE @EmployeeTotal int

EXECUTE spGetEmployeeCountByGender @EmployeeCount = @EmployeeTotal OUT, @Gender = ‘Male’

PRINT @EmployeeTotal

SQL5

Now let’s have a quick look at some of the extremely useful system stored procedures.

  • sp_help SP_Name : Used to view the information about the stored procedure like parameter names, their datatypes etc. sp_help can be used with any database object, like Tables, Views, SPs, Triggers etc. Alternatively, you can also press ALT+F1, when the name of the object is highlighted.

Let’s see this is in action. If we want to find out more information about the stored procedure we have just created, we can use sp_help spGetEmployeeCountByGenderWhile executing this, we could see the name of the stored procedure, type, created date, parameters, their data types etc.

SQL6

You can use sp_help with any database objects like Tables, Views, Triggers etc. For example, when we use sp_help with tblEmployee table, we will get all the information about the table like different columns present in the table, their data types, indexes associated with the table, constraints associated with the table etc.

SQL7

  • sp_helptext SP_Name : Used to view the Text of the stored procedure.

For example, when we use sp_helptext spGetEmployeeCountByGender, we will get the text of this stored procedure.

SQL8

  • sp_depends SP_Name : Used to view the dependencies of the stored procedure. This system stored procedure is very useful, especially if you want to check whether there are any stored procedures that are referencing a table which you are about to drop. sp_depends can also be used with other database objects like Tables, Views etc.

SQL10

In the above example, sp_depends tblEmployee statement gives a result that there is a stored procedure which is dependent on tblEmployee table.  So you have to be extremely careful while dropping this table.

Reference: Arun Ramachandran (http://BestTEchnologyBlog.Com)

ASP.Net MVC – Different kinds of Templated Helpers

In the last blog post, we have discussed about HiddenInput and ReadOnly attributes in ASP.Net MVC. You can read that article here. In this article we will go over different kinds of Templated Helpers.

 Templated Helpers are introduced in MVC 2. These built in Templated Helpers can be broadly classified into 2 categories.

  1. Display Templates
  2. Editor Templates

There are 3 kinds of Display Templated Helpers.

  1. @Html.DisplayForModel() - Used with strongly typed views. This templated helper will walk through each property in the model to display the object.
  2. @Html.Display(“EmployeeData”) - Used with a view that is not strongly typed. For example, if we have stored data in ViewData, then we can use this templated helper using the key that was used to store data in ViewData.
  3. @Html.DisplayFor(model => model) - Used with strongly typed views. If your model has properties that return complex objects, then this templated helper is very useful.

Let’s understand the use of Display Templated Helpers with an example. We will be using the same example which we have used in the previous article.

In the Home controller, we already have Details and Edit action methods implemented. We have Details and Edit Views as well. But now, I am going to delete them and readd the Details View. For this, right click on the Details action method and select Add View.

Set View name=Details, Model class=tblEmployee, Scaffold template=Details and click on Add.

MVC1
This should add Details.cshtml View. Notice that there are a lot of HTML generated for this.

MVC2
Let’s run the solution and navigate to Details action in Home controller. We can see the employee’s full details.

MVC3
But within our View, there are a lot of HTML. Instead of this, let’s use DisplayForModel() Templated Helper. If you look at the Details View, a model object – tblEmployee is associated with the View. So this is a Strongly typed view. Instead of all the HTML, simply use @Html.DisplayForModel(). This templated helper is going to walk through each property in the tblEmployee object and inspects that property’s metadata.

@model MVCDemo.Models.tblEmployee

@{
ViewBag.Title = “Details”;
}

<h2>Details</h2>

<fieldset>
<legend>tblEmployee</legend>

@Html.DisplayForModel()

</fieldset>

MVC4
Let’s build the solution and refresh the View. The output is going to be exactly the same.

MVC5
We can use @Html.Display templated helper when we are dealing with a View that is not Strongly typed.

Let’s understand this with an example. Previously, we were passing tblEmployee object to the View. But now, I am going to store tblEmployee object in ViewData.

public ActionResult Details(int id)
{
SampleDBContext db = new SampleDBContext();
tblEmployee employee = db.tblEmployees.Single(x => x.Id == id);

ViewData["EmployeeData"] = employee;

return View();
}

MVC6
In the Details View, I am going to get rid of the model. Now the View is not a Strongly typed one. Since it is not a Strongly typed view, I can’t use DisplayForModel() templated helper. So I am going to use Display templated helper like below.

@{
ViewBag.Title = “Details”;
}

<h2>Details</h2>

<fieldset>
<legend>tblEmployee</legend>

@Html.Display(“EmployeeData”)

</fieldset>

MVC7
Let’s build the solution and refresh the View. The output should be exactly same as before.

Just like 3 Display Templated Helpers, there are 3 Edit Templated Helpers as well.

  1. @Html.EditorForModel()
  2. @Html.Editor(“EmployeeData”)
  3. @Html.EditorFor(model => model)

Let’s quickly look at the use of one of the Edit templated helper. Within our Home controller, there is Edit action method.

public ActionResult Edit(int id)
{
SampleDBContext db = new SampleDBContext();
tblEmployee employee = db.tblEmployees.Single(x => x.Id == id);
return View(employee);
}

EditActionMethod
Right click on this action method and select Add View. Set View name=Edit, Model class=tblEmployee, Scaffold template=Empty and click on Add.

MVC8
Inside the Edit.cshtml View, use EditorForModel() templated helper like below.

@model MVCDemo.Models.tblEmployee

@{
ViewBag.Title = “Edit”;
}

<h2>Edit</h2>

@using (@Html.BeginForm())
{
@Html.EditorForModel()
}

MVC9
Let’s build the solution and navigate to Edit action in the Home controller. We will get the editing interface like below.

MVC10
To associate metadata with model class properties, we use attributes. In the previous articles, we have discussed about using various data annotations attributes. These templated helpers use metadata associated with the model to render the user interface.

ThankYou
Reference: Arun Ramachandran (http://BestTEchnologyBlog.Com)

ASP.Net MVC – HiddenInput and ReadOnly attributes

In the last blog post, we have discussed about opening the page in a new browser window in ASP.Net MVC. You can read that article here. In this article we will go over HiddenInput and ReadOnly attributes.

HiddenInput attribute is useful when you want to render a property using input type=hidden. This attribute is extremely useful when you don’t want the user to see or edit the property, but you need to post the property value to the server when the form is submitted, so the correct record can be updated. HiddenInput is present in System.Web.Mvc namespace.

Let’s try to understand this with an example. We will be using the same example which we have used in the previous article. Notice that when we navigate to Details action method within Home controller, we can see the employee’s full details including the Id property.

MVC1

But we don’t want to allow the user to see the Id property. To achieve this, we can simply decorate the Id property within the Employee class with HiddenInput attribute.

MVC2

Let’s build our solution and refresh the View. We can see that the Id is now hidden.

MVC3

Let’s check whether we can see the Id while we try to edit the Employee details. For this, first step is to implement Edit action method within the Home controller. Modify the Edit action method like below.

public ActionResult Edit(int id)
{
    SampleDBContext db = new SampleDBContext();
    tblEmployee employee = db.tblEmployees.Single(x => x.Id == id);
            
    return View(employee);
}

MVC4

The next step is to implement Edit View. Right click on the Edit action method and select Add View.

MVC5

Copy and paste the following code to Edit.cshtml.

<div style=”font-family:Arial”>

@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <br />
    <br />
    <input type=”submit” value=”Save” />
}
</div>

EditView

With all these changes, let’s build the solution and navigate to Edit mode. Notice that we can see the employee’s full details except the Id property.

MVC6

If we right click on the page and select View page source, we can see an input element with name=Id, type=hidden and value=3. So when we click on the Save button, the Id of the employee also will be posted to the server and we can use that Id to update the correct employee record.

MVC7

The next attribute that we are going to discuss is ReadOnly attribute. ReadOnly attribute is present in System.ComponentModel namespace. As the name suggests, this attribute is used to make a property read only. Please note that we will still be able to change the property value on the view, but once we post the form, the model binder will respect the ReadOnly attribute and will not move the value to the property.

For example, if we decorate the EmailAddress with ReadOnly property, we will still be able to change that on the View. But when we submit the form, the default model binder in ASP.Net MVC will not move that value from the posted form values to the class properties.

Let’s look at this in action. First of all, decorate the EmailAddress with ReadOnly attribute.

MVC8

Within the Home controller, we need to implement the Edit action method that respond to the Post operation. Copy and paste following code to the Edit action method.

[HttpPost]
public ActionResult Edit(tblEmployee employee)
{
if (ModelState.IsValid)
{
SampleDBContext db = new SampleDBContext();
tblEmployee employeeFromDB = db.tblEmployees.Single(x => x.Id == employee.Id);

// Populate all the properties except EmailAddrees
employeeFromDB.FullName = employee.FullName;
employeeFromDB.Gender = employee.Gender;
employeeFromDB.Age = employee.Age;
employeeFromDB.HireDate = employee.HireDate;
employeeFromDB.Salary = employee.Salary;
employeeFromDB.PersonalWebSite = employee.PersonalWebSite;
var Manager = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager;
Manager.ChangeObjectState(employeeFromDB, System.Data.Entity.EntityState.Modified);
db.SaveChanges();
return RedirectToAction(“Details”, new { id = employee.Id });
}
return View(employee);
}

 MVC9

Notice that we are populating all the properties except the EmailAddress. Let’s put a break point inside the Edit action method and run the solution in debug mode. Let’s change FullName to Priyanka2, Gender to Female2. Let’s also change the EmailAddress to Priyanka2@BestTEchnologyBlog.com.

MVC10

After these modifications, when we click on the Save button, notice that all the properties are changed except the EmailAddress. EmailAddress is null because we have decorated EmailAddress property with ReadOnly attribute. So it is not going to receive any value from the posted form.

MVC11

If we press F5, the new values will be saved and we will be redirected back to the Details action method. Notice that FullName, Gender have changed, but EmailAddress has no change.

MVC12

 We can also make property of a class readonly simply by removing the SET accessor.

MVC13

Reference: Arun Ramachandran (http://BestTEchnologyBlog.Com)

ASP.Net MVC – Hyperlinks – Open the page in a new browser window

In the last blog post, we have discussed about DataType & DisplayColumn attributes in ASP.Net MVC. You can read that article here. In this article we will look at how to open the page in a new browser window while clicking on a hyperlink.

Let’s understand this with an example. We will be using the same example which we have used in the previous article. First of all, change the Details action method in the Home controller like below.

public ActionResult Details(int id)
{
SampleDBContext db = new SampleDBContext();
tblEmployee employee = db.tblEmployees.Single(x => x.Id == id);
return View(employee);
}

MVC1

Then change the Details View like below.

MVC2

Build the solution and run it. At this point, we should be able to see the employee’s full details.

MVC3

Notice that PersonalWebSite property is rendered as a hyperlink. It is because within the tblEmployee class, we have decorated the PersonalWebSite property with DataType attribute.

MVC4

Right click on the page and select View page source. Notice the anchor tag generated here. It has a href attribute, but doesn’t have a target attribute.

MVC5

We know that if we want a Url to open in a new window, the target attribute needs to be set to _blank. Since this anchor tag doesn’t have a target attribute, when we click on the hyperlink, the target page is going to open in the same window.

MVC6

Let’s see how to open the Url in a new window. Follow the below steps.

  • Right click on Views folder and add Shared folder.
  • Right click on Shared folder and add DisplayTemplates folder.
  • Right click on DisplayTemplates folder and add a View. Set Url as the name and use Razor view engine.

MVC7

Notice the name of the View here. It matches the enum value DataType.Url. Then Copy and paste the following code in Url.cshtml view.

<a href=”@ViewData.Model” target=”_blank”>@ViewData.Model</a>

MVC8

Now build the solution and refresh the View. Let’s right click on the page and select View page source. Notice the anchor tag right here. Now we have a target attribute which is set to _blank.

MVC9

If we click on the link now, the Url should be opened in a new window.

MVC10

But the downside of this approach is that, from now onwards all the links will be opened in a new window. But our requirement is such that only PersonalWebSite should be opened in a new window. Rest of the links within our application need to be opened in the same window. For this, 2 simple modifications have to be done.

  1. Rename Url.cshtml to OpenInNewWindow.cshtml
  2. Decorate PersonalWebSite property in EmployeeMetaData class with UIHint attribute and specify the name of the template to use. In our case, the name of the template is OpenInNewWindow.

public class EmployeeMetaData
{
    [DataType(DataType.Url)]
    [UIHint("OpenInNewWindow")]
    public string PersonalWebSite { get; set; }
}

MVC11

Now run the application and we can see that except the PersonalWebSite, all the other links will be opened in the same window.

From the above example itself , it is clear that UIHint attribute is used to specify the name of the template to use to display the data field.

Reference: Arun Ramachandran (http://BestTEchnologyBlog.Com)

 

ASP.Net MVC – What are the uses of DataType and DisplayColumn attributes?

In the last blog post, we have discussed about Display, DisplayName, DisplayFormat and ScaffoldColumn attributes in ASP.Net MVC. You can read that article here. In this article we will continue with DataType and DisplayColumn attributes.

Let’s understand these with an example. I am taking the same example which we have used in the previous article. There we have seen that while running the application, the email address is showing as a plain text.

MVC15

Instead, we want the email address to be rendered with mailto hyperlink. The advantage of this is that when we click on that hyperlink, it is going to open the default email address of the client automatically.

To achieve this, you simply need to decorate the EmailAddress property within the EmployeeMetaData class with DataType attribute.

MVC1

Let’s run the application. We can now see that Email Address is rendered with a mailto hyperlink.

MVC2

Another scenario where you can use DataType attribute is when you want to associate currency symbols. Look at the page, at the moment Salary is displayed without any symbols. We want to associate a currency symbol with the Salary. Let’s use DataType attribute again for this purpose.

MVC3

Let’s build our solution by pressing Ctrl+Shift+B and refresh the View. We can see that now Salary is displayed with a $ symbol by default in my machine.

MVC4

But instead, we want to associate some other currency symbol, say Indian Rupees with this amount. To achieve this, in Web.config file, specify culture using globalization element.

MVC5

Save the changes and refresh the View. We can now see a Rupees symbol instead of a $ symbol.

MVC6

Now look at the Personal Web Site. At the moment, it is displaying as a plain text. Instead, we want that has to be displayed as a hyperlink. We can achieve this very easily. One simple thing you have to do is decorate that property with DataType attribute.

MVC7

Build the solution and refresh the View, we can see that now Personal Web Site is rendered as a hyperlink. While clicking on the hyperlink, you will be navigated to this blog.

MVC8

Now let’s look at the use of DisplayColumn attribute. DisplayColumn attribute is useful, when a class has a property of complex type and you want to pick one property of this complex object for display purpose. Let’s understand this with an example.

First of all, right click on the Models folder and add Company.cs class file.

MVC9

Copy and paste the following code.

public class Company
{
    public tblEmployee CompanyDirector
    {
        get
        {
            SampleDBContext db = new SampleDBContext();
            return db.tblEmployees.Single(x => x.Id == 1);
        }
    }
}

MVC10

Notice that this class has CompanyDirector property which returns a tblEmployee object. tblEmployee is a complex type. tblEmployee object has got several properties. If you want FullName to be used for display purpose, then make the following changes.

Decorate tblEmployee partial class in Models folder, with DisplayColumn attribute.

DisplayColumn

Change Details action method in Home controller as shown below.

public ActionResult Details(int id)
{
    Company company = new Company();
    return View(company);
}

MVC11

Copy and paste the following code in Details.cshtml view.

@model MVCDemo.Models.Company

@{
    ViewBag.Title = “Details”;
}

@Html.DisplayTextFor(x => x.CompanyDirector)

MVC12

Now run the application and navigate to localhost:57506/MVCDemo/Home/Details/3. You should see the Full Name of the employee.

MVC13

Reference: Arun Ramachandran (http://BestTEchnologyBlog.Com)

ASP.Net MVC – What are the uses of Display, DisplayName, DisplayFormat and ScaffoldColumn attributes?

In the last blog post on ASP.Net MVC, we have discussed about implementing ListBoxes. You can read that article here. In this article we will go over different display attributes  in ASP.Net MVC.

Let’s understand this with an example. We will be using tblEmployee table for this. The SQL scripts for creating tblEmployee table and inserting data into it are following:

Create table tblEmployee
(
Id int primary key identity,
FullName nvarchar(100),
Gender nvarchar(10),
Age int,
HireDate DateTime,
EmailAddress nvarchar(100),
Salary int,
PersonalWebSite nvarchar(100)

Insert into tblEmployee values
(‘George Thomas’, ‘Male’, 37, ’2014-02-03 16:50:47.788′, ‘GeorgeThomas@BestTEchnologyBlog.com’, 40000, ‘www.BestTEchnologyBlog.com’)

Insert into tblEmployee values
(‘Priyanka’NULL, 29, ’2014-03-05 09:53:36.678′, ‘Priyanka@BestTEchnologyBlog.com’, 36000,‘www.BestTEchnologyBlog.com’)

First of all, generate an ADO.NET Entity data model for the table tblEmployee. You can refer here to know the steps to be followed to create an ADO.NET Entity data model.

EntityDataModel

Then right click on the Controllers folder and add HomeController.

MVC2

MVC3

Include the following USING statement to HomeController.

using MVCDemo.Models;

Copy and paste the following code.

public class HomeController Controller
{

 public ActionResult Details(int id)
{
SampleDBContext db = new SampleDBContext();
tblEmployee employee = db.tblEmployees.Single(x => x.Id == id);
return View(employee);
}

}

MVC4

Then right click on the Details action method and add Details view. Make sure that you are creating a strongly typed view against tblEmployee class. Select Details as the Scaffold template.

MVC5

Set Aerial as our font – family by using a div tag.

MVC6

Build the Solution and run it. We will get a screen like below.

MVC8

But look at the output , it is not much pretty. There is no space in between Full and Name and is displaying as FullName. Gender is showing as blank. We have to make it much more pretty. The text should be Full Name instead of FullName and if Gender is not specified, instead of showing blank there, a text of Gender not specified should be appeared. How can we achieve this? Here comes the importance of display attributes.

We can control the display of data in a View using display attributes that are found in System.ComponentModel.DataAnnotations namespace. It is not a good idea to add display attributes to the properties of auto-generated tblEmployee class as our changes will be lost if the class is auto-generated again.

So let’s create another partial Employee class and decorate that class with the display attributes. Right click on the Models folder and add Employee.cs class file.

MVC9

Copy and paste the following code. Notice that I have tried to include the purpose of each attribute through the comments. Please read them carefully.

namespace MVCDemo.Models
{
    [MetadataType(typeof(EmployeeMetaData))]
    public partial class tblEmployee
    {
    }

    public class EmployeeMetaData
    {
        //If you want “FullName” to be displayed as “Full Name”, 
        //use DisplayAttribute or DisplayName attribute.
        //DisplayName attribute is in System.ComponentModel namespace.
        //[DisplayAttribute(Name="Full Name")]
        //[Display(Name = "Full Name")]
        [DisplayName("Full Name")]
        public string FullName { get; set; }

        //To get only the date part in a datetime data type
        //[DisplayFormat(DataFormatString = "{0:d}")]
        //[DisplayFormatAttribute(DataFormatString="{0:d}")]

        //To get time in 24 hour notation

        //[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm:ss}")]

        //To get time in 12 hour notation with AM PM

        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss tt}")]
        public DateTime? HireDate { get; set; }

        // If gender is NULL, “Gender not specified” text will be displayed.
        [DisplayFormat(NullDisplayText = "Gender not specified")]
        public string Gender { get; set; }

        //If you don’t want to display a column use ScaffoldColumn attribute.
        //This only works when you use @Html.DisplayForModel() helper
        [ScaffoldColumn(false)]
        public int? Salary { get; set; }
    }
}

MVC10

Don’t forget to include following using statements:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

Now build the solution and run it. We can see a page like below.

MVC11

Here everything is OK except the Salary. Even if we have used [ScaffoldColumn(false)] attribute for the Salary, it is still showing. I think you can guess the reason. In the comments itself, I have specified that ScaffoldColumn attribute will work only when we use @Html.DisplayForModel() helper.

So instead of all the HTML in the View, we will get the same output by just adding one line of code which is shown below.

@Html.DisplayForModel()

This HTML helper will go through each property and will render the UI automatically.

MVC14

Now let’s build the solution by pressing Ctrl+Shift+B and refresh the page. We can see that the Salary is now hidden.

MVC15

Reference: Arun Ramachandran (http://BestTEchnologyBlog.Com)