ASP.Net Web Services – Different attribute properties of a WebMethod

In the last blog post, we have discussed about how to use session state in a  web service. In this article we will go over different WebMethod attribute properties like Description, BufferResponse and CacheDuration.

This is continuation of the previous article. So please go through that before proceeding this article to get a clear idea. You can read that article here.

Description - Use to specify a description for the web service method.

Let’s understand this property with an example. We have already implemented 2 methods within the CalculatorWebService – Add and GetCalculations. At the moment, none of these methods display any description.

WebServices1

We want to associate some description with the Add method. To achieve this, specify Description property with the WebMethod.

WebServices2

Let’s view the web service in a browser. Notice that the description we have specified is displayed with the method.

WebServices3

BufferResponse – This is a boolean property whose default value is true. When this property is true, the response of the XML Web service method is not returned to the client until either the response is completely serialized or the buffer is full. 

On the other hand, when this property is false, the response of the XML Web service method is returned to the client as it is being serialized.

In general, set BufferResponse to false only when the XML Web service method returns large amounts of data. For smaller amounts of data, web service performance is better when BufferResponse is set to true.

CacheDurationUse this property if you want to cache the results of a web service method. This is an integer property and it specifies the number of seconds that the response should be cached. The response is cached for each unique parameter.

Let’s understand the CacheDuration property with an example. Let’s view the current webform in a browser. At the moment, when we click on Add button, each time the web service method will be processed and response will be returned. Even if we send same parameters, the web service method will be executed and the response will be sent back.

WebServices4

But when we send the same parameters, there is no point in re-executing it. So it is better to cache the response of the web service method to improve the performance of the application. Use CacheDuration property for this. If we specify CacheDuration property to say 20, then the response of the method will be cached for 20 seconds.

WebServices5

Build the web service and Update Service Reference. This process will regenerate the proxy class.

WebServices6

Now view the webform in a browser. For the first time, if we click on Add method with some parameters, the web service method will be processed and the result should be cached for 20 seconds. If we leave the parameters as same and click on Add method again, if we are within the 20 seconds, the web service method will not be processed. Instead, the response which is stored in the cache will be returned to the client.

WebServices7

On the other hand, if the 20 seconds are elapsed, then the web method will be reprocessed and the response will be cached for another 20 seconds.

WebServices8

But if we change the parameters and click on Add method, since these are different parameters, a separate response will be cached.

WebServices9

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

ASP.Net Web Services – How to use session state in a web service?

In the last blog post, we have discussed about consuming web services from the client application. In this article we will go over how to use session state in a web service.

This is continuation of the previous article. So please go through that before proceeding this article to get a clear idea. You can read that article here.

To use ASP.NET Session object in a web service, there are 2 things we need to do.

  1. The WebService class should inherit from System.Web.Services.WebService class.
  2. The EnableSession property of the WebMethod attribute should be set to true.

WebService1

While looking at our CalculatorWebService class, we can see that it is already inherited from System.Web.Services.WebService class. But we need to set EnableSession property to true.

In this article, we will be trying to display the recent calculations using a session object in a GridView like below.

Purpose

To achieve this, first of all, modify the Add method of CalculatorWebService class like below.

[WebMethod(EnableSession = true)]
        public int Add(int firstNumber, int secondNumber)
        {
            List<string> calculations;

            if (Session["CALCULATIONS"] == null)
            {
                calculations = new List<string>();
            }
            else
            {
                calculations = (List<string>)Session["CALCULATIONS"];
            }
            
            string strTransaction = firstNumber.ToString() + ” + ” 
                + secondNumber.ToString() 
                + ” = ” + (firstNumber + secondNumber).ToString();
            calculations.Add(strTransaction);
            Session["CALCULATIONS"] = calculations;

            return firstNumber + secondNumber;
        }

WebService2

Then include another public method to return all the calculations. Decorate this method with WebMethod attribute and set EnableSession property to true.

[WebMethod(EnableSession = true)]
        public List<string> GetCalculations()
        {
            if (Session["CALCULATIONS"] == null)
            {
                List<string> calculations = new List<string>();
                calculations.Add(“You have not performed any calculations”);
                return calculations;
            }
            else
            {
                return (List<string>)Session["CALCULATIONS"];
            }
        }

WebService3

Now build the solution and view our web service in a browser.

WebService4

The web service should list 2 methods – Add and GetCalculations.

WebService5

Click on the Add method. Let’s add 2 numbers, say 20 and 30. While clicking on the Invoke button, we will get the result as 50.

WebService6

WebService7

Let’s do another calculation, say 30 and 70. While clicking on the Invoke button, we will get the result as 100.

WebService8

WebService9

Now let’s go back and test our GetCalculations method. While clicking on the Invoke button, all the calculations we have performed until now are displayed. They will be returned as an array of strings.

WebService10

So our web service is working as expected. Now let’s try to use these methods in our client web application. For that, within the Webform1.aspx, let’s drag and drop a GridView control.

<tr>
    <td>
        <asp:GridView ID=”gvCalculations” runat=”server”>
        </asp:GridView>
    </td>
</tr>

WebService11

Before the code behind file modifications, we need to update the proxy class. To do this, right click on the CalculatorService and select Update Service Reference.

WebService12

After that, within the btnAdd_Click event, add the following lines of codes.

gvCalculations.DataSource = client.GetCalculations();
            gvCalculations.DataBind();

            gvCalculations.HeaderRow.Cells[0].Text = “Recent Calculations”;

WebService13

Build the solution and view the webform in a browser.
WebService14

Let’s go ahead and add 2 numbers, say 20 and 30. But even though we have performed one calculation, a message of You have not performed any calculations will be displayed.

WebService15

This is basically because the web application is not sending the same SessionId to the web service. To make it work, set allowCookies to true in web.config file.

WebService16

Let’s run the webform once again and add some numbers. Now we can see that this is working as expected.

WebService17

So points here to ponder are following:

  • If web service has changed, the proxy class in the client application needs to be updated. To do this, right click on the service in Service Reference folder and select Update Service Reference option.
  • Set allowCookies attribute to true for the client application to accepts the cookie returned from the ASMX web service and to copy it into all future requests that are made to the web service. This ensures that the same Session is maintained between the client and the web service.

What’s next?

In the next article, we will discuss about WebMethod attribute properties.

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

ASP.Net Web Services – How to consume a web service from a client application?

In last day, we were discussing about creating ASP.Net Web Services. You can read that article hereIn this article, we will go over consuming a web service from a client application.

Let’s try to consume the web service which we have created in the previous article. Follow the below steps for this.

Step 1Right click on WebServicesDemo solution in Solution Explorer and add a new ASP.Net Web Application Project and name it as CalculatorWebApplication.

ASP.NetWebServices1

Step 2Now we need to add a reference to the web service. To achieve this, first right click on the References folder in the CalculatorWebApplication project and select Add Service Reference option.

ASP.NetWebServices2

Then in the Address textbox of the Add Service Reference window, type the web service address and click on GO button. In the Namespace textbox, type CalculatorService and click OK.

ASP.NetWebServices3

Once we click OK, Visual Studio will create a Proxy Class based on the WSDL document. Under the Service References folder, we can see the Namespace we have provided which is CalculatorService.

ASP.NetWebServices4

If you want to look at the generated Proxy Class, first click on the Show All Files button on the top. Then you can see a file named Reference.cs. 

ASP.NetWebServices7

Open that file. You can see a class called CalculatorWebServiceSoapClient. This is the Proxy Class. Inside this class, you can see an Add method which is very much similar to the Add method in the CalculatorWebService.

ASP.NetWebServices8

Step 3Right click on CalculatorWebApplication project in Solution Explorer and add a new Web Form named WebForm1.aspx.

Step 4Copy and paste the following HTML into the Web Form.

<table style=”font-family: Arial”>
<tr>
    <td>
        <b>First Number</b>
    </td>
    <td>
        <asp:TextBox ID=”txtFirstNumber” runat=”server”></asp:TextBox>
    </td>
</tr>
<tr>
    <td>
        <b>Second Number</b>
    </td>
    <td>
        <asp:TextBox ID=”txtSecondNumber” runat=”server”></asp:TextBox>
    </td>
</tr>
<tr>
    <td>
        <b>Result</b>
    </td>
    <td>
        <asp:Label ID=”lblResult” runat=”server”></asp:Label>
    </td>
</tr>
<tr>
    <td colspan=”2″>
        <asp:Button ID=”btnAdd” runat=”server” Text=”Add” 
        OnClick=”btnAdd_Click” />
    </td>
</tr>
</table>

ASP.NetWebServices5

Step 5: Copy and paste the following code to the button click event in the code behind file.

protected void btnAdd_Click(object sender, EventArgs e)
{
CalculatorService.CalculatorWebServiceSoapClient client =
               new CalculatorService.CalculatorWebServiceSoapClient();
int result = client.Add(Convert.ToInt32(txtFirstNumber.Text),
                Convert.ToInt32(txtSecondNumber.Text));
lblResult.Text = result.ToString();
}

ASP.NetWebServices6

Now right click on the WebForm1.aspx and select View in Browser. Give some First Number & Second Number, say 20 and 30 and click on Add button. You will get a result as 50 as expected.

ASP.NetWebServices9

Here if we look at the web application, we don’t have the logic of adding two numbers. The addition is actually done by the web service. The client application accesses the web service using HTTP protocol. Messages with web services are exchanged in SOAP format. The Serialization which is converting .Net types to SOAP request messages and Deserialization which is converting SOAP response back into .Net types are done by Proxy Class which in our case is CalculatorWebServiceSoapClient class.

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

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)