Sunteți pe pagina 1din 133

Custom validators in ASP.

Net MVC
How to add custom validators in mvc4?

Create MVC project

Select basic project


Add Sample controller
Add Customer.cs file to use as model while creating View.

Add View in Sample Controller


Select strongly type view and select customer.cs
Now Add Required Attribute on property of customer - above Name

Required inbuilt property for validation after adding using


System.ComponentModel.DataAnnotations;

This required attribute make that textbox mandatory.

public class Customer


{
[Required]
public string Name { get; set; }
}

We have to add custom validator like need some special word in textbox
value.

Then just write [RequiredSpecialWord] and press ctrl + . and create class

Now check RequiredSpecialWord.cs in model folder. It inherited from


ValidationAttribute class

Now override method isValid in RequiredSpecialWord.cs


Check below code

public class RequiredSpecialWord:ValidationAttribute


{
private string _word;
public RequiredSpecialWord(string word)
{
_word = word;
}
protected override ValidationResult IsValid(object value, ValidationContext
validationContext)
{
if (Convert.ToString(value).Contains(_word))
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(_word +" not included");
}
}
}

Check ModelState.IsValid property in controller.

public ActionResult contact(Customer cust)


{
if (!ModelState.IsValid)
{
return View("index");
}
return View();
}

ModelState.IsValid checks that your validation are valid or not.

Now just run your project and add sample/Index in your browser url after
localhost.

And see output

After clicking submit button. You will get below result. Because we added
Required validator and we have not put anything in textbox.
Now I entered text as aaaa and pressed submit, then I got below result

That is Ram not included. Ram is normal word it can be Rob, Dan anything.

To change Ram word use below code in customer.cs

[RequiredSpecialWord("Ram")]
public string Name { get; set; }

Using this method you can reset all controls in windows form in GroupBox and
save time for writing code to reset all controls individually.

Code for Reset Controls

void ResetAll(GroupBox gbox)


{
foreach (Control ctrl in gbox.Controls)
{
if (ctrl is TextBox)
{
TextBox textBox = (TextBox)ctrl;
textBox.Text = null;
}
if (ctrl is ComboBox)
{
ComboBox comboBox = (ComboBox)ctrl;
comboBox.SelectedIndex = -1;
}
if (ctrl is CheckBox)
{
CheckBox checkBox = (CheckBox)ctrl;
checkBox.Checked = false;
}
if (ctrl is RadioButton)
{
RadioButton radioButton = (RadioButton)ctrl;
radioButton.Checked = false;
}
if (ctrl is ListBox)
{
ListBox listBox = (ListBox)ctrl;
listBox.ClearSelected();
}
}
}

Introduction To Entity Framework

What is Entity Framework?

It is an Object Relational Mapper (ORM) that enables programmers to communicate with


a relational database.

What is ORM?

Object Relational Mapper: processing a relational database and mapped in such way so
as programmers can use it in their code easily.

Why Entity Framework?

Using this we can do all the DB select, insert, update, delete operations without writing
ADO .Net code that we write for every single query of a database.

1. To do the faster development use Entity Framework

2. Connect with any database like SQL or Oracle

3. Auto-generated Model

4. Works well with Stored Procedures

First create a table in your database: I have attached my DB structure here.


Now in Visual Studio add a new item: ADO entity Model.
Select your database and save the entity to do CRUD operations.
Select your tables.
After clicking on Finish an edmx is created for your project.

Now

Create Entity Object to do CRUD operations

1. FirstDayEntities ObjEntity = new FirstDayEntities();


2.
3. #region Read All Merchants
4. var ObjMerchantsList = ObjEntity.Merchants;
5. #endregion
6.
7. #region Insert
8. Merchant ObjMerchant = new Merchant() { Name = "Mangesh Gaherwar", Address =
"Solapur" };
9. ObjEntity.AddToMerchants(ObjMerchant); // ObjEntity.Merchants.AddObject(ObjMerch
ant); //both r same
10. int InsertResult = ObjEntity.SaveChanges();
11. #endregion
12.
13. #region Update
14. Merchant ObjUpdateMerchant = ObjEntity.Merchants.Where<Merchant>(a => a.Nam
e == "Mangesh Gaherwar").FirstOrDefault();
15. ObjUpdateMerchant.Address = "Kamote";
16. int UpdateResult = ObjEntity.SaveChanges();
17. #endregion
18.
19. #region Delete
20. Merchant ObjDeleteMerchant = ObjEntity.Merchants.Where<Merchant>(a => a.Name
== "Mangesh Gaherwar").FirstOrDefault();
21. ObjEntity.Merchants.DeleteObject(ObjDeleteMerchant);
22. int DeleteResult = ObjEntity.SaveChanges();
23. #endregion

That's it.

If your database table structure is the same then only change the connection string in
the web.config

Executing Stored Procedure using Entity Framework

First write a Stored Procedure in your database as in the following.

This procedure takes one input parameter @MerchantID and returns the Name and
Address of the respective merchant id.

1. Create PROCEDURE [dbo].[USP_GetMerchantDetails] --1


2. (
3. @MerchantID int
4. )
5. AS
6. BEGIN
7. select Name, Address from Merchant where id=@MerchantID
8. END

To add an entity model to your project check Entity Framework in Day1.

You can select the procedure at the time of creation of the entity model.

Otherwise you can add it after the creation of the project.

Use the following procedure to create a sample.


1. Double-click on Day2Model.dmx.

2. Then you will get a edmx diagram screen. Right-click on the that screen and
select model browser.
3. Then right-click on Stored Procedure of MyModel.store and select Update Model
from Database.
4. Check your procedure and finish, then automatically your procedure execution
function will be created. You can change the return type also after addition of the
procedure.
Now your model browser looks like:
Entity type: Merchant - consider as simple Merchant Table
Complex Type: USP_GetMerchantDetails_Result - Return Type of Stored Procedure, we
can use this when we want to return multiple table columns, like M.MerchantName and
p.ProductName.
Function Imports: USP_GetProductDetails - execute function
Same in Stored Procedure: USP_GetProductDetails - you will get the option on this
procudre to change and add functions

Check your code generated in Day2Model.Designer.cs.

1. public ObjectResult<USP_GetMerchantDetails_Result> USP_GetMerchantDetails(Nullable<


global::System.Int32> merchantID)
2. {
3. ObjectParameter merchantIDParameter;
4. if (merchantID.HasValue)
5. {
6. merchantIDParameter = new ObjectParameter("MerchantID", merchantID);
7. }
8. else
9. {
10. merchantIDParameter = new ObjectParameter("MerchantID", typeof(global::Sys
tem.Int32));
11. }
12.
13. return base.ExecuteFunction<USP_GetMerchantDetails_Result>("USP_GetMerchan
tDetails", merchantIDParameter);
14. }

So now call the auto-generated procedure function and execute the Stored Procedure.

Complex Return Type

1. MyModel.MyEntities Obj = new MyModel.MyEntities();


2. var qq = Obj.USP_GetMerchantDetails(1); //1 is merchantid
Debug result:

Entity Return Type

To add a new function for a Stored Procedure click on:

Now click the Entity dropdown and select respective Entity.


The following is the code to call this function:

1. MyModel.MyEntities Obj = new MyModel.MyEntities();


2. var Result = Obj.USP_GetMerchantDetails_Entity(1);

Every time check your generated code in the designer.cs file.

The difference between complex type functions and entity type functions to execute a
procedure.

1. Everything is the same except return type

The following is the auto-generated code of the entity type and complex type:
Paging in Entity Framework

Use custom paging to increase performance.

Just mention the current page number, page size and entity to return the current page
record.
1. protected void Page_Load(object sender, EventArgs e)
2. {
3. MyModel.MyEntities Obj = new MyModel.MyEntities();
4. ObjectSet<Merchant> MerchantList = Obj.Merchants;
5. var CurrentRecords = GetCurrentPageRecords(3, 2, MerchantList);
6. }
7. public IEnumerable<Merchant> GetCurrentPageRecords(int CurrentPageNumber, int Page
Size, ObjectSet<Merchant> MerchantList)
8. {
9.
return MerchantList.OrderBy(s => s.Id).Skip(PageSize * CurrentPageNumber - 1).Take(Page
Size).Select(a => a);
10. }

Sorting in Entity Framework

Just mention the current column Name, order by state, page number, page size and
entity to return the current page record with sort.

1. var CurrentRecordswithsort = GetSortingRecords("name_desc",3, 2, MerchantList);


2.
3. public IEnumerable<Merchant> GetSortingRecords(string ColumnNameWithAscDesc,int
CurrentPageNumber, int PageSize ,ObjectSet<Merchant> MerchantList)
4. {
5. switch (ColumnNameWithAscDesc.ToLower())
6. {
7. case "id":
8. return MerchantList.OrderBy(s => s.Id).Skip(PageSize * (CurrentPageNumber - 1
)).Take(PageSize).Select(a => a);
9. case "id_desc":
10. return MerchantList.OrderByDescending(s => s.Id).Skip(PageSize * (CurrentPag
eNumber - 1)).Take(PageSize).Select(a => a);
11. case "name":
12. return MerchantList.OrderByDescending(s => s.Name).Skip(PageSize * (Current
PageNumber - 1)).Take(PageSize).Select(a => a);
13. case "name_desc":
14. return MerchantList.OrderByDescending(s => s.Name).Skip(PageSize * (Current
PageNumber - 1)).Take(PageSize).Select(a => a);
15. default:
16. return MerchantList.OrderBy(s => s.Id).Skip(PageSize * CurrentPageNumber - 1)
.Take(PageSize).Select(a => a);
17. }
18.
19. }

create a normal Stored Procedure so we can execute that Stored Procedure in the
following scenarios.

Stored Procedure

1. Create PROCEDURE [dbo].[USP_GetCustomerByID]


2. (
3. @CustomerID int
4. )
5. AS
6. BEGIN
7. SELECT * from Customer where id=@CustomerID
8. END

The Stored Procedure is now created and I assume you understand all the basics of the
Entity Framework.

So, Let's start; it's very easy.

1. How to execute an raw SQL query

The following is another way to execute a SQL query without calling entity
functions:

1. using (var ObjEntity = new CRMModel.CRMEntities())


2. {
3. var GetAllCustomer = ObjEntity.ExecuteStoreQuery<Customer>("select * from cust
omer");
4. }

2. The following executes a Stored Procedure without mapping the Stored Procedure
function in edmx; pass a parameter in the same as we pass one in SQL Managmet
Studio, so you will get an appropriate procedure output.

1. using (var ObjEntity = new CRMModel.CRMEntities())


2. {
3. var Cuetomer1 = ObjEntity.ExecuteStoreQuery<Customer>("USP_GetCustomerByI
D 1");
4. }
3. The following executes Insert/Update/Delete Statements using the
ExecuteCommand function, in other words without creating an entity:

1. using (var ObjEntity = new CRMModel.CRMEntities())


2. {
3. var UpdateResult= ObjEntity.ExecuteStoreCommand("update customer set Name='
saip' where id=1");
4. }

Note: Before running the source code please change the web.config connection string.

ASP.Net MVC 4 Crunch

This article will take you through the ASP.NET MVC 4 description and design templates in
details, such as what templates are available in ASP.NET MVC 4 and how effectively you
can use them depending on your use. This article also includes the functions of templates
and the basics of how they work.

In spite of all this content this article also includes the functionality of the Razor View
Engine and MVC application structure.

MVC specifies options for how the project should be created.

Application Templates

There are several templates available in ASP.NET MVC 4 development work. These
templates are as follows:

The internet application template

The intranet application template

The basic template

The empty template

The mobile application template

The web API template

The internet application template

This contains the beginning of an MVC web application, enough that you can run
the application immediately after creating it and see a few pages. The template
also includes some basic account management functions that run against the
ASP.NET membership system depending on your development work.
The intranet application template

The intranet application template was added as part of the AS.NET MVC 3 tools
update. It is similar to the internet application template. But the account
management functions run against Windows accounts rather than the ASP.NET
membership system.

The basic template

The template is pretty minimal. It still contains:

Running an application created using the empty template gives you an error
message.

The basic template is intended for experienced MVC developers who want to set
up and configure how you want them to be.

The Empty Template

In the most general cases the basic Template is called an Empty Template, but
developers have some issues regarding this matter. They complained that it
wasn't quite empty enough. So with MVC 4, the previous empty template was
renamed Basic and the new Empty Template is about as empty as you can get.

The Mobile Application Template

The mobile application template is re configured with jQuery mobile to jump start
creating a mobile only website. It includes these most important base structures
or we can say the functionalities:
The Web API Template

The ASP.NET web API is nothing but a framework for creating HTTP services. The
web API template is similar to the internet application template. Web API
functionality is also available in the other MVC project template and even in non-
MVC project types.

Razor View Engine (RVE)

The Razor View Engine is one of the most popular and useful features that was in MVC
3. Further it is improved with more advanced functionality in MVC 4.

The razor engine has been the first major update to rendering HTML since ASP.NET 1
shipped almost a decade ago. It was something new that developers were looking for,
none at that time was familiar with that fact that this "Razor Engine, which is neither a
new language nor a puppet or a framework" will be a trump card of MVC in developing
network based applications.

The default view engine used in MVC 1 and MVC 2 for rendering functionality was
commonly called Web Forms View Engine, because it applies the same
ASPX/ASCX/MASTER files and syntax generally used in web courses.

It was planned to support editing controls in a graphical editor or any editor that can be
utilized for delivering functionality.

Structure View | RVE

The structural position of a Razor engine is something like:


(For a more elaborate survey of the Razor View Engine, please proceed through this
article link: Razor View Engine in MVC)

MVC Application Structure

When you create a new MVC application with Visual Studio, it automatically adds several
files and directories to the project. These directories are:

1. /Controllers

The directory where you placed your controller classes that handle the URL
requests. When we expand the controller directory, it shows two sub-controller
directories:
o HomeController

o AccountController

2. /Models

The directory where you placed your classes that represent and manipulate data
and business objects. It contains three sub-directories:

o Account

o Home

o Shared

3. /View

The directory where you placed your UI template files that are responsible for
rendering output, such as HTML.

4. /Scripts

The directory where you placed your JavaScript library files and scripts.

5. /Images

The directory where you placed your images being used in the site.

6. /Content

The directory where you placed your CSS and other site content, other than
scripts and images used.

7. /Filters

The directory where you placed your filter code. Filter is the advanced feature of
MVC. It comes into light along with MVC 4.

8. /App_Data

The directory where you placed your data files, on which you need to do
Read/Write operations.

9. /App_Start

The directory where you placed your configuration code for features like:
Routing

Bundling

Web API

Downloading and Uploading File Using


WCF REST Services With Windows
Authentication
WCF REST Service

The first step is to create a WCF REST service that will be used for downloading and
uploading the file. I prefer to keep all my services in a separate WCF project. This project
is then hosted in the IIS.

1. Add a new Blank solution by the name of FileHandling.

2. Add a new WCF Service Application and give it the name FileHandling.WCFHost.

3. Right-click the FileHandling.WCFHost project in Visual Studio and go to the


properties. Under the Web tab click on Use local IIS WebServer and under the
Project URL, write http://localhost/FileHandling.WCFHost and click on the button
Create Virtual Directory. This will create a Virtual Directory for
FileHandling.WCFHost in IIS.
4. Go to IIS and check if the Virtual Directory is created.

5. Ensure that the App Pool associated to the account is of .Net Framework 4.0. Also,
the App Pool should be running under the identity of the user that has Read/write
rights on any folder of the server. WCF uses this identity for doing all its network
operations. In this case I run the App Pool under my account, but it is not
mandatory, you can choose a different account having permissions as well.
6. Ensure that for the FileHandling.WCFHost, only Windows Authentication is
enabled.
With the preceding steps the IIS configuration is complete. Now it's time to add
the service.

7. Add a new WCFService in the FileHost.WCFHost project in VisualStudio and give it


the name FileManagerService.

8. In the IFileManagerService add the following methods.

1. using System.IO;
2. using System.ServiceModel;
3. using System.ServiceModel.Web;
4.
5. namespace FileHandling.WCFHost
6. {
7. [ServiceContract]
8. public interface IFileManagerService
9. {
10.
11. [OperationContract]
12. [WebGet(UriTemplate = "RetrieveFile?Path={path}")]
13. Stream RetrieveFile(string path);
14.
15. [OperationContract]
16. [WebInvoke(UriTemplate = "UploadFile?Path={path}")]
17. void UploadFile(string path, Stream stream);
18.
19. }
20. }

9. In the FileManagerService.svc.cs add the following code:

1. using System;
2. using System.IO;
3. using System.ServiceModel.Web;
4.
5. namespace FileHandling.WCFHost
6. {
7. public class FileManagerService : IFileManagerService
8. {
9. public Stream RetrieveFile(string path)
10. {
11. if(WebOperationContext.Current == null) throw new Exception("WebOper
ationContext not set");
12.
13. // As the current service is being used by a windows client, there is no brow
ser interactivity.
14. // In case you are using the code Web, please use the appropriate content t
ype.
15. var fileName = Path.GetFileName(path);
16. WebOperationContext.Current.OutgoingResponse.ContentType= "applicatio
n/octet-stream";
17. WebOperationContext.Current.OutgoingResponse.Headers.Add("content-
disposition", "inline; filename=" + fileName);
18.
19. return File.OpenRead(path);
20. }
21.
22. public void UploadFile(string path, Stream stream)
23. {
24. CreateDirectoryIfNotExists(path);
25. using (var file = File.Create(path))
26. {
27. stream.CopyTo(file);
28. }
29. }
30.
31. private void CreateDirectoryIfNotExists(string filePath)
32. {
33. var directory = new FileInfo(filePath).Directory;
34. if (directory == null) throw new Exception("Directory could not be determ
ined for the filePath");
35.
36. Directory.CreateDirectory(directory.FullName);
37. }
38. }
39. }

The RetrieveFile method is used for downloading the file. The method takes the
parameter path, that is the location of the file for downloading from the WCF
server. The method itself is pretty simple, it sets the ContentType and filename in
the Response Header and then sends the FileStream back. Do not worry about
how this FileStream will be disposed. WCF automatically takes care of it and at the
end of the method disposes of it.

The UploadFile is also pretty simple. It takes the following two parameters:

1. path: Path where the uploaded file should be saved

2. stream: Stream represents the Uploaded file.

The method creates the Directory if it does not already exist and then creates the
file in the location specified by path. For copying the uploaded file in the path
location, Stream.CopyTo has been used.

o It's time to add the configuration settings for the service. In the Web.Config
add the following configuration.

1. <system.serviceModel>
2. <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
3. <bindings>
4. <webHttpBinding>
5. <binding name="ServiceWebBindingName" transferMode="Streamed" maxRe
ceivedMessageSize="2147483647" >
6. <readerQuotas maxArrayLength="2147483647" maxStringContentLength=
"2147483647" />
7. <security mode="TransportCredentialOnly">
8. <transport clientCredentialType="Windows"></transport>
9. </security>
10. </binding>
11. </webHttpBinding>
12. </bindings>
13. <behaviors>
14. <endpointBehaviors>
15. <behavior name="DefaultRestServiceBehavior">
16. <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrap
ped" automaticFormatSelectionEnabled="false"/>
17. </behavior>
18. </endpointBehaviors>
19. <serviceBehaviors>
20. <behavior name="">
21. <serviceMetadata httpGetEnabled="true" />
22. <serviceDebug includeExceptionDetailInFaults="true" />
23. </behavior>
24. </serviceBehaviors>
25. </behaviors>
26. <services>
27. <service name="FileHandling.WCFHost.FileManagerService">
28. <endpoint address=""
29. binding="webHttpBinding"
30. bindingConfiguration="ServiceWebBindingName"
31. behaviorConfiguration="DefaultRestServiceBehavior"
32. name="FileManagerServiceEndpoint"
33. contract="FileHandling.WCFHost.IFileManagerService"/>
34. </service>
35. </services>
36. </system.serviceModel>
37. </configuration>

Please note that the Transfermode has been set to Streamed. This will ensure
that the file is streamed to the client. And also, notice that I have given maximum
values to maxReceivedMessageSize, maxArrayLength, maxStringContentLength.
This will ensure that large files can be transferred as well.

38. <binding name="ServiceWebBindingName" transferMode="Streamed" maxReceiv


edMessageSize="2147483647" >
39. <readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147
483647" />
40. <security mode="TransportCredentialOnly">
41. <transport clientCredentialType="Windows"></transport>
42. </security>
43. </binding>
44. </webHttpBinding>
45. </bindings>

Also note that for Security mode has been set to TransportCredentialsOnly and the
ClientCredentialType has been set to Windows.

Client

Now it's time to build the Client.


I decided to use a simple Windows client for consuming the WCF service for downloading
and uploading the file. Methods for uploading and downloading are specified below.

FileUpload

The UploadFileToRemoteLocation method takes the following 2 parameters:

filePath: specifies the local path of where the file is located.

destinationFilePath: specifies the path on the server (on which WCF is hosted)
where file must be uploaded.

The method UploadFileToRemoteLocation copies the file specified in the filePath to the
request stream. It then calls the WCF service for uploading this file and passes
destinationFilePath as the path where the file should be stored on the server.

The service on being called receives the file and then saves it at the destinationFilePath
on the server.

In this example both WCFHost and the client are located on the same server but the
WCFHost can be located on any other server as well.

1. /// <summary>
2. /// Uploads file to remote location
3. /// </summary>
4. private void UploadFileToRemoteLocation(string filePath, string destinationFilePath)

5. {
6. var serviceUrl = string.Format("{0}/UploadFile?Path={1}", FileManagerServiceUrl,
destinationFilePath);
7. var request = (HttpWebRequest)WebRequest.Create(serviceUrl);
8. request.Method = "POST";
9. request.UseDefaultCredentials = true;
10. request.PreAuthenticate = true;
11. request.Credentials = CredentialCache.DefaultCredentials;
12.
13. using (var requestStream = request.GetRequestStream())
14. {
15. using (var file = File.OpenRead(filePath))
16. {
17. file.CopyTo(requestStream);
18. }
19. }
20.
21. using (var response = request.GetResponse() as HttpWebResponse)
22. {
23. // Do Nothing
24. }
25.
26. }

FileDownload

The method DownloadFileFromRemoteLocation takes the following 2 parameters:

downloadFileLocation: This is path on the server where the file is located.

downloadedFileSaveLocation: This is the local path where the file is saved


after downloading.
The DownloadFileFromRemoteLocation method first downloads file from the service and
then stores the file in the path specified in downloadedFileSaveLocation.

1. private void DownLoadFileFromRemoteLocation(string downloadFileLocation, string dow


nloadedFileSaveLocation)
2. {
3. string serviceUrl = string.Format("{0}/RetrieveFile?Path={1}", FileManagerServic
eUrl, downloadFileLocation);
4. var request = WebRequest.Create(serviceUrl);
5. request.UseDefaultCredentials = true;
6. request.PreAuthenticate = true;
7. request.Credentials = CredentialCache.DefaultCredentials;
8.
9. try
10. {
11. using (var response = request.GetResponse())
12. {
13. using (var fileStream = response.GetResponseStream())
14. {
15. if (fileStream == null)
16. {
17. MessageBox.Show("File not recieved");
18. return;
19. }
20.
21. CreateDirectoryForSaveLocation(downloadedFileSaveLocation);
22. SaveFile(downloadedFileSaveLocation, fileStream);
23. }
24. }
25.
26. MessageBox.Show("File downloaded and copied");
27.
28. }
29. catch (Exception ex)
30. {
31. MessageBox.Show("File could not be downloaded or saved. Message :" + ex.Mes
sage);
32. }
33.
34. }
35.
36. private static void SaveFile(string downloadedFileSaveLocation, Stream fileStream)

37. {
38. using (var file = File.Create(downloadedFileSaveLocation))
39. {
40. fileStream.CopyTo(file);
41. }
42. }
43.
44. private void CreateDirectoryForSaveLocation(string downloadedFileSaveLocation)
45. {
46. var fileInfo = new FileInfo(downloadedFileSaveLocation);
47. if (fileInfo.DirectoryName == null) throw new Exception("Save location directory
could not be determined");
48. Directory.CreateDirectory(fileInfo.DirectoryName);
49. }

Please refer to the attached code if you would like to have a look at the complete working
solution.

The following are the prerequisites for the attached code to work:

IIS should be installed.


.Net Framework 4.0 should be installed

Visual Studio 2010 or above.

Creating Websites in ASP.NET


The Visual Studio project system allows you to define a new Web Site project based on
how you intend to access the site content from a web server.

You can create a Web project connected to a File system based on your computer, an IIS
server or an FTP server. This helps in how you run, manage and deploy your Web site
project.

Following are the location of your Web project:

1. File system

2. HTTP

3. FTP

File System

The File System option creates the new website in a location on your hard drive or on
your shared network drive. Using such a file system Web site means that you do not need
to create your site as an Internet Information Services (IIS) application to develop or test
it.

.NET 2.0 onward versions Microsoft launched ASP.NET Development Server with .NET
Framework which work as an attached process when any Web Application executes.
ASP.NET Development Server comes along with .NET

In ASP.NET Development Server instance is created as attached process in File System.

File systems Web sites are particularly useful in the following situations:

When you do not want to (or cannot) install IIS on your development computer.

When you already have a set of Web files in a folder, and you want to use Visual
Web Developer to open them as a project.

In classroom settings, where students can store files on student-specific folders on


a central server.

In a team setting, where team members can access a common Web site on a
central server.

File System is used till the process of development, after development it is used in
FTP/HTTP server.

HTTP

An HTTP based Web site is used when you are working with a site deployed inside of IIS
(either locally or on a remote server). This Web site may be configured at the root of the
IIS Web server or in a virtual directory that is configured as an application.

Note: A remote server running IIS will have to provide access to your Web files using
Front page Server extension.

In this application will be created under IIS (Internet Information Services) server.

In HTTP your web application is stored under IIS home directory. You will not get any
instance of ASP.NET Development server. No port is specified. The request will be
handled at IIS port only.

Creating or opening a local IIS Web site is useful in the following situations:

You want to test your Web site using IIS, which closely emulates how the Web site
will run on a production server. This can have advantages over working with file
system Web sites that run using the ASP.NET Development Server, because paths
are resolved as they will be on a production server.

You already have a set of Web site files in a folder and you want to test the Web
site with IIS. In this case, you can create a virtual directory in your local version of
IIS.

Your local computer is also your Web server.

You can create file system of your choice but you have to map with IIS server. We map
with the help of Virtual Directory.

How to create a virtual directory?

Follow the steps given below:

Step 1: Run the inetmgr from taskbar - >run

Step 2: Right click on Default Web Site and click on New -> Virtual Directory
Step 3: Click on Next Button
Step 4: Give a name of you choice to your virtual directory.

Step 5: Select the physical path on your hard disk or sharable network drive.
Step 6: Check the permission you want to set for the Virtual Directory.
Step 7: Click on Finish. You are done.

FTP

FTP location provides direct facility of creating application at FTP.


The FTP based Web site is useful when you want to connect to your web site via FTP to
manage your files on a remote server. This option is typically used when your website is
hosted on a remote server computer and your access to the files and folders on that
server is through FTP.

Selecting FTP is essentially the same but creates the site on a server that is accessed
using the FTP (File Transfer Protocol).

In FTP your application work on two modes debug mode and release mode.

Choosing HTTP or FTP generally requires that you have a username and password for a
location on a server provided by a web host.

FTP by default is not secure. When a user login to a server his/her information is sent as
plain text.

There is more information about FTP and FTP Active Mode and Passive Model, which I
have not mentioned here.

Hosting WCF Service inside IIS


Windows Communication Foundation:

Windows Communication Foundation(WCF) takes many existing communication


technologies, such as Web Services, Windows Remoting, Microsoft Message Queuing,
and abstracts them into a single technology. In most cases, this simplifies the way you
communicate with other applications. It also allows you to communicate with other
applications without being coupled to a specific technology. In this we are going to create
a simple WCF service and we are going to host that service inside SharePoint 2010 .

Steps Involved:
Create a WCF Service:

The following steps should be followed to create a WCF service using Visual Studio 2010.

I. Open Visual Studio 2010.

ii. Go to File => New => Project.

iii. Select WCF Service Application under installed template category WCF and name it as
Wcf.

iv. Target the .Net Framework 3.5.

v. Click OK.

vi. In the Solution Explorer delete Service.svc and IService.cs files.

vii. Right click the Solution Explorer and add a New Item.

viii. Select WCF Service and name it as CustomService.svc.


ix. Replace ICustomerService.cs with the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace Wcf

{
[ServiceContract]
public interface ICustomService
{
[OperationContract]
string GetTime();
}
}

x. Replace CustomerService.svc.cs with the following code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace Wcf
{
public class CustomService : ICustomService
{
public string GetTime()
{
return DateTime.Now.ToString();
}
}
}

xi. In the Web.config file remove the below code.


<service behaviorConfiguration="Wcf.Service1Behavior" name="Wcf.Service1">
<endpoint address="" binding="basicHttpBinding" contract="Wcf.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
<behavior name="Wcf.Service1Behavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
xii. Now Save the project and Build the application.

Add a new Web Site:

I. Start Internet Information Services (IIS) Manager. Click Start => All Programs =>
Administrative Tools => Internet Information Services (IIS) Manager.

ii. In Internet Information Services (IIS) Manager, right-click on Sites, and select Add
Web Site.
iii. In the Add Web Site dialog box, in the Site name field, enter WCF. In the Physical
path field, enter C:\Users\kfcb554pa.tst\Desktop\Project\Wcf\Wcf. In the Port field,
enter 6000 and click OK.
iv. Validate that the web service is running. Start Internet Explorer, and browse to
http://ukcbemtsekikm01:6000/CustomService.svc. (Note: ukcbemtsekikm01 is the
server name). If the web service is running, you will see the following:
v. Another approach to test the Web service is to use the WCF test client. Start a Visual
Studio command prompt. Enter wcftestclient to run the WCF test client.

vi. Click File => Add Service.

vii. Enter http://ukcbemtsekikm01:6000/CustomService.svc as the endpoint address,


and click OK.

viii. If the service was added successfully, you will see the methods that the service
exposes as shown below.

ix. Double-click on GetTime. This opens a window that allows you to configure the
request and invoke the request.
x. Thus the WCF has been created and hosted inside SharePoint 2010.

Configuring ASP.NET with IIS

Problem

The problem arises when you install IIS after installing ASP.NET. If you do this, IIS will
configure itself for the ASP.NET version that ships with your Windows edition that might
be an older version (e.g. version 2.0) and you won't be able to run any web application
built using a later version of ASP.NET.

Solution

The solution is simply to reconfigure ASP.NET for IIS. You don't need to reinstall ASP.NET
or the .NET Framework; you just need to reapply ASP.NET configuration to the IIS.

When you open the IIS Manager, you can check Application Pools and see which version
of ASP.NET is currently configured. Here, we have IIS installed after ASP.NET, so the IIS
is configured for version 2.0 (as you can see in figure 1.)

To solve this, we'll get help from the aspnet_regiis.exe tool that will reconfigure IIS to
the version of ASP.NET you choose. This tool is located in %windir
%\Microsoft.NET\Framework\v<version> (replace <version> with the version of .NET
Framework you like to use.)

Let's get this done. Open the Command Prompt in administrative mode (Start->Cmd-
>Ctrl+Shift+Enter) and go to the .NET Framework directory mentioned before.
Now, run the ASP.NET IIS Registration tool using the following command:

aspnet_regiis.exe -i

When the tool finishes its job, you'll get a message inform you that everything was
completed successfully.

Now go to IIS Manager again and check the Application Pools. You can now find that IIS
is configured for ASP.NET 4.0 which is installed on that machine (see figure 2.)

Enjoy your day!

How To Deploy ASP.Net Web site Content


on IIS 7.0

Introduction on IIS 7

Now we will see the Home Screen for IIS 7.0 :


Create a virtual directory on IIS 7.0 :
Once you have created a Virtual directory, copy the published folder content to the
Virtual Directory:

Step 1: From Visual Studio 2005 or above, publish your web application.

Step 2: Copy the published application folder content to the

"C:\intepub\wwwroot\YourVirtualDir" folder.

Step 3: From RUN - > inetmgr -> OK

Authentication Settings:

You can change Security Settings in the Authentication Section. By default the setting
will be set from your web.config. Since in my web.config, Form Authentication was set,
that's why Forms Authentication was Enabled. If we want to change the status, just
double click and update the status to Enabled or to Disabled or Vice Versa.
Configure IIS to host your website without
Asp.net

This article describes how to set up IIS on your PC then host your web site without
Visual Studio Installed.

If you want, in a Client's machine if you don't install Visual Studio but want to host your
website in it then you can do this. It can be very usefull for you.

Step 1 : Install IIS on Your Server Machine

Go with this way .

Start -> Control Panel -> Add Remove Programs -> Add/Removes Windows
Components.

Then click on Window Component Wizard Internet Information Service (IIS)


Click the Checkbox for Internet Information Service (IIS) then click the next button and
select browse to XP Installation CD for Required Files.

Then install the .Net Framework.


Step 3: After Installation Set Your Web Site For hosting

After IIS installation, on the C drive the Inetpub folder is created.

Copy and paste your web site folder into the wwwroot folder.

Inetpub -> wwwroot -> yourwebsitefolder

Step 4: After pasting your folder is set on the default web site.

Right-click on My Computer then click the manage option.

Manage -> Computer management (Local) -> Internet Information Service -> Website
-> Default Web Site.

On right-click default Web Site Click New -> Virtual Directory.

On Virtual Directory Creation Wizard click next then set Alias Name.

After write alias name click next and browse your directory on wwwroot folder website . .
then set all Access Permission Checked.

Read...Write...Browse
After finishing check the .Net Framework version; on right-click for your web site
properties on the ASP.NET tab. If the version is not selected then choose it ASP.Net
Version and set it.

Then browse to your web site.

And in the client machine that you want to run the web site in, give the URL with server
IP address.

http://192.168.192.1/Onlineshoping/Index.aspx.

Security model of Internet Information


Services for ASP.NET

IIS has its own security configuration and even for any request reaching the ASP.NET
runtime, IIS verifies the request with it's own security configuration. So the first
gatekeeper in the ASP.NET security pipeline is actually IIS. So let us understand those
security mechanisms which IIS implements:
1. Authentication: IIS support following authentication mechanism

Basic authentication:

Digest authentication

Passport authentication

Window authentication

Certificate authentication

Point to remember:
1. Any authentication which IIS performs results into an authenticated window user,
so this means that IIS supports authenticating window users only.

2. If ASP.NET is configured to support form or window authentication, then configure


IIS to support basic or digest authentication.

3. If ASP.NET is configured to support form or custom authentication, then configure


IIS to support anonymous access.

4. With XP, it comes with IIS 5.x

5. With Server 2003, it is IIS 6.0

How to configure IIS for authentication:

Point to member here

1. When the Anonymous User option is checked then everyone is given access to a
web page and it overrides all authentication settings.

2. If IIS is configured to anonymous authentication, we can still use ASP.NET-based


security to authenticate users either with ASP.NET-integrated mechanisms such as
forms authentication or a custom type of authentication.
3. Windows authentication configures IIS to validate the credentials of the user
against a Windows account configured either on the local machine or within the
domain. A Credential submitted by a user is verified against the Windows
account.

4. When Basic Authentication is checked it defines an additional HTTP header for


transmitting user names and password across the wire but nothing is encrypted
here. It is transmitted in the form of a base64 encoding.

5. Digest authentication is similar to basic authentication with the difference that


instead of sending credentials in the form of Base64 encoding, user password and
username are hashed.

2. Authorization (IIS 6.0) Here we can configure the IP address restriction with IIS.
This gives us the privilege to restrict access to the web server from a machine
specified in the list
So here we learned about security configurations in different versions of IIS-from IIS
5.x and IIS 6.0.

you need to set Permissions for Virtual directory inside IIS7, On clicking virtual dirc. ->
then in Features View there is an option Application Settings .. here you will need to
Edit Permission for Network Service to Full Control .

Deploying Web Applications using IIS


Express

I am using a Windows 7 Home Basic in my Laptop . It does not have a IIS . I was
really struggling to take the advantage of IIS in my system . But now using IIS
Express I can easy take advantage of IIS . Lets see how simple it is to deploy Web
applications using IIS Express .

Download IIS Express from the following site as shown below :


http://www.microsoft.com/download/en/details.aspx?id=1038

It is a 3 Mb download . Download and install it in your system .

Once the Installation is completed .

Browse to the path :

C:\Program Files (x86)\IIS Express and click on the iisexpress application .

IIS Express would be started as shown below :

Open up Visual Studio . Open any Web Project which you would like to host .
I have opened a Silverlight project here .

Our aim is not to use the Visual Studio Deployment Server as I have already said.

So right click on the Web project .

Select Use IIS Express .

The following message would appear . Say Yes .

Visual Studio would prompt a message as shown below . Say Ok .


You could see the IIS Express icon in the current running tasks list as shown below :

Make the web project as start up. Run the project .

Click on right click on the IIS Express and say show all applications .

IIS Express Opens up .


Now we can browse our application as shown below :

How To Deploy ASP.Net Web site Content


on IIS 7.0
Introduction on IIS 7

Now we will see the Home Screen for IIS 7.0 :

Create a virtual directory on IIS 7.0 :


Once you have created a Virtual directory, copy the published folder content to the
Virtual Directory:

Step 1: From Visual Studio 2005 or above, publish your web application.

Step 2: Copy the published application folder content to the

"C:\intepub\wwwroot\YourVirtualDir" folder.

Step 3: From RUN - > inetmgr -> OK

Authentication Settings:

You can change Security Settings in the Authentication Section. By default the setting
will be set from your web.config. Since in my web.config, Form Authentication was set,
that's why Forms Authentication was Enabled. If we want to change the status, just
double click and update the status to Enabled or to Disabled or Vice Versa.
CRUD Operation in ASP.Net MVC
Framework

Objective:

The core purpose of this article is to demonstrate how to perform CRUD operation on a
database in ASP.NET MVC Framework.

See my other articles on ASP.NET MVC Framework to get an understanding of different


components of framework.

My articles could be found at

Introduction Here

Output Caching Here

About Controller here

Silverlight in MVC Framework here

Final output would be something like


Data Base Description

1. I have created one database called ContactDetails in SQL Server 2008.

2. ContactDetails database contains one table called Author_Contact_Details


3. Id is a primary key and its (Is Identity) property is set to the value Yes.

Note: Database script is being attached to download. So either you could run that
database script or you could create the database manually by yourself.

Creating MVC application

1. Open visual studio and create new Project -> Web -> Asp.Net MVC Application.
2. Create UNIT Test project as well. We will do unit testing on our project later in this
article or next series of this article.

3. After creating application Solution Explorer will look like below. It would contain
Model, View and Controller folders.
4. There will be one more project in solution for Unit Testing.

5. Delete the following files from the ASP.NET MVC project


\Controllers\HomeController.cs
\Views\Home\About.aspx
\Views\Home\Index.aspx

6. And delete the following file from the Test project


\Controllers\HomeControllerTest.cs

Creating the Data Model

1. Right click on Models and add New Item


2. From Data tab select Ado.Net Entity data model.

3. Give any meaningful name for .edmx . Here name is


Author_Contact_DetailsModel.
4. Select "Generate from Database".
5. Choose Data Source name. Choose Server Name. Select Database.

6. Click on "Test Connection" to check the connection.

7. Give Connection string name and click next. Here connection string name is
ContactDetailsEntities.
8. Select table and give model namespace name. Here model namespace name is
ContactDetailsModel
At this point, we have created our database model. We can use the
Author_Contact_Details class to represent a particular contact record in our
database.

Creating the Home Controller


1. Right click on Controller and select Add Controller.

2. Give Controller name. Controller name must be post fixed by Controller . Here
name is HomeController. You cannot give any name. Controller name must be
followed by Controller.

3. Checked the box to add action methods for Create, Update and Delete When you
create the Home controller, you get the class like below

Controller\HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

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

public ActionResult Index()


{
return View();
}

//
// GET: /Home/Details/5

public ActionResult Details(int id)


{
return View();
}

//
// GET: /Home/Create

public ActionResult Create()


{
return View();
}

//
// POST: /Home/Create

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here

return RedirectToAction("Index");
}
catch
{
return View();
}
}

//
// GET: /Home/Edit/5

public ActionResult Edit(int id)


{
return View();
}

//
// POST: /Home/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here

return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}

Note: _entities is initialized globally.

4. Now that we've created the Index controller, we next need to create the Index
view. Before creating the Index view, compile application by selecting the menu
option Build, Build Solution. You should always compile your project before adding
a view in order for the list of model classes to be displayed in the Add View dialog.

5. Right click at Index and select Add View

6. Select "Create a Strongly typed view". From View data class select name of the
table and in View content select List.
7. Un modified Index.aspx will look like below

Views\Home\Index.aspx (unmodified)

<%@ Page Title="" Language="C#"


MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<AuthorContactDetail.Models.
Author_Contact_Details>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"


runat="server">
Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent"


runat="server">

<h2>Index</h2>

<table>
<tr>
<th></th>
<th>
Id
</th>
<th>
FirstName
</th>
<th>
LastName
</th>
<th>
Phone
</th>
<th>
Email
</th>
</tr>

<% foreach (var item in Model) { %>

<tr>
<td>
<%= Html.ActionLink("Edit", "Edit", new { id=item.Id }) %> |
<%-- <%= Html.ActionLink("Details", "Details", new { id=item.Id })%>--
%>
</td>
<td>
<%= Html.Encode(item.Id) %>
</td>
<td>
<%= Html.Encode(item.FirstName) %>
</td>
<td>
<%= Html.Encode(item.LastName) %>
</td>
<td>
<%= Html.Encode(item.Phone) %>
</td>
<td>
<%= Html.Encode(item.Email) %>
</td>
</tr>

<% } %>

</table>

<p>
<%= Html.ActionLink("Create New", "Create") %>
</p>

</asp:Content>

Note: Here, Details Link is commented, because we don't have any details of
record.

Just press F5 to run with debugging.


Creating New Contacts

If you see at Controller\HomeController.cs, for creating new contacts you will find
code below.

// GET: /Home/Create

public ActionResult Create()


{
return View();
}

//
// POST: /Home/Create

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here

return RedirectToAction("Index");
}
catch
{
return View();
}
}

//
// GET: /Home/Edit/5

1. First Create() action that returns an HTML form for creating a new contact

2. Second Create () action is performing actual insertion into table.

3. First Create () action is attributed with HTTP GET verb. So it would return HTML
page.

4. Second Create () action is attributed with HTTP POST verb. So it would post data in
database.

5. Second Create () action could only be called while posting the HTML form.

6. We need to modify second Create action to perform actual Insertion into


database.

public ActionResult Create()


{
return View();
}

//
// POST: /Home/Create

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="Id")] Author_Contact_Details
contactDetail)
{

if (!ModelState.IsValid)
return View();
try
{
// TODO: Add insert logic here
_entities.AddToAuthor_Contact_Details(contactDetail);
_entities.SaveChanges();

return RedirectToAction("Index");
}
catch
{
return View();
}
}

7. Right click on either of the Create action and add Create View
8. Select Create a Strongly Typed View and in View Content select Create
9. Create.aspx file will get created in View/Home. The .aspx will look like below

View/Home/Create.aspx

<%@ Page Title="" Language="C#"


MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AuthorContactDetail.Models.Author_Contac
t_Details>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"


runat="server">
Create
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent"


runat="server">

<h2>Create</h2>

<%= Html.ValidationSummary("Create was unsuccessful. Please correct the


errors and try again.") %>

<% using (Html.BeginForm()) {%>

<fieldset>
<legend>Fields</legend>
<p>
<label for="Id">Id:</label>
<%= Html.TextBox("Id") %>
<%= Html.ValidationMessage("Id", "*") %>
</p>
<p>
<label for="FirstName">FirstName:</label>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>
</p>
<p>
<label for="LastName">LastName:</label>
<%= Html.TextBox("LastName") %>
<%= Html.ValidationMessage("LastName", "*") %>
</p>
<p>
<label for="Phone">Phone:</label>
<%= Html.TextBox("Phone") %>
<%= Html.ValidationMessage("Phone", "*") %>
</p>
<p>
<label for="Email">Email:</label>
<%= Html.TextBox("Email") %>
<%= Html.ValidationMessage("Email", "*") %>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>

<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>

</asp:Content>

Just press F5 to run with debugging.


Editing Contacts

If you see at Controller\HomeController.cs , for editing contacts you will find code
below.

// GET: /Home/Edit/5

public ActionResult Edit(int id)


{
return View();
}

//
// POST: /Home/Edit/5

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here

return RedirectToAction("Index");
}
catch
{
return View();
}
}

1. The first Edit() method is invoked by an HTTP GET operation. An Id parameter is


passed to this method which represents the Id of the contact record being edited.
The Entity Framework is used to retrieve a contact that matches the Id. A view
that contains an HTML form for editing a record is returned.

2. The second Edit() method performs the actual update to the database. This
method accepts an instance of the Contact class as a parameter. The ASP.NET
MVC framework binds the form fields from the Edit form to this class
automatically.

3. Notice that you don't include the [Bind] attribute when editing a Contact (we need
the value of the Id property).

4. We need to modify the Edit action to perform actual operation

Controller\HomeController.cs

// GET: /Home/Edit/5

public ActionResult Edit(int id)


{

var res = (from r in _entities.Author_Contact_Details where r.Id == id


select r).FirstOrDefault();
return View(res);
}

//
// POST: /Home/Edit/5

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Author_Contact_Details contactDetail)
{

if (!ModelState.IsValid)
return View();
try
{
// TODO: Add update logic here
var res = (from r in _entities.Author_Contact_Details where r.Id ==
contactDetail.Id select r).FirstOrDefault();
_entities.ApplyPropertyChanges(res.EntityKey.EntitySetName,
contactDetail);
_entities.SaveChanges();

return RedirectToAction("Index");
}
catch
{
return View();
}
}

5. Right click at either of Edit action and add View

6. Create a Strongly typed View. Select table name and in View content select Edit.
Just press F5 to run with debugging.

Deleting Contacts

Controller\HomeController.cs

public ActionResult Delete(int Id)


{
var res = (from r in _entities.Author_Contact_Details where r.Id == Id select
r).FirstOrDefault();
return View(res);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(Author_Contact_Details contactDetail)
{
try
{
var res = (from r in _entities.Author_Contact_Details where r.Id ==
contactDetail.Id select r).FirstOrDefault();
_entities.DeleteObject(res);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}

1. The first Delete() action returns a confirmation form for deleting a contact record
from the database.

2. The second Delete() action performs the actual delete operation against the
database. After the original contact has been retrieved from the database, the
Entity Framework DeleteObject() and SaveChanges() methods are called to
perform the database delete.

3. In Index.aspx and add below line of code there

<%= Html.ActionLink("Delete", "Delete", new { id=item.Id })%>

Index.aspx

<%@ Page Title="" Language="C#"


MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<AuthorContactDetail.Models.
Author_Contact_Details>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"


runat="server">
Index
/asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent"


runat="server">

<h2>Index</h2>

<table>
<tr>
<th></th>
<th>
Id
</th>
<th>
FirstName
</th>
<th>
LastName
</th>
<th>
Phone
</th>
<th>
Email
</th>
</tr>

<% foreach (var item in Model) { %>


<tr>
<td>
<%= Html.ActionLink("Edit", "Edit", new { id=item.Id }) %> |
<%= Html.ActionLink("Delete", "Delete", new { id=item.Id })%>
</td>
<td>
<%= Html.Encode(item.Id) %>
</td>
<td>
<%= Html.Encode(item.FirstName) %>
</td>
<td>
<%= Html.Encode(item.LastName) %>
</td>
<td>
<%= Html.Encode(item.Phone) %>
</td>
<td>
<%= Html.Encode(item.Email) %>
</td>
</tr>

<% } %>

</table>

<p>
<%= Html.ActionLink("Create New", "Create") %>
</p>

</asp:Content>

4. Right click either of Delete action and add View


5. Create a Strongly typed view and select View content Empty.

Just press F5 to run with debugging.


Changing the caption of the site
1. Go to Views -> Shared -> Site.Master

2. Change the title and save master page.

<div id="title">
<h1>C# Corner Author's Contact Details</h1>
</div>

Just press F5 to run with debugging.


Summary:

This article explained about, how to perform CRUD operation on a table in ASP.Net MVC
Framework.

Add a Controller in MVC

Let's discuss how to add Controller in an MVC application:

Just go in to solution explorer of your application -> Controller -> Add


->Controller,just like in the billow image:
A new dialogue box ll open click on add, do like bellow image :
A new HelloworldController.cs file ll be available in controller folder in
solution explorer,just like in below image:

Replace the default code to :

using System.Web;
using System.Web.Mvc;

namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/

public string Index()


{
return "This is my <b>default</b> action...";
}

//
// GET: /HelloWorld/Welcome/

public string Welcome()


{
return "This is the Welcome action method...";
}
}
}

Now this code ll return a string of html with the


address http://localhost:5891/HelloWorld ,like :
And http://localhost:5891/HelloWorld/welcome ll show like bellow
image:

Let's modify the example slightly so that you can pass some parameter information from
the URL to the controller (for example, /HelloWorld/Welcome?
name=Scott&numtimes=4). Change your Welcome method to include two parameters as
shown below. Note that the code uses the C# optional-parameter feature to indicate that
thenumTimes parameter should default to 1 if no value is passed for that parameter.

public string Welcome(string name, int numTimes = 1) {


return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes);
}

Run your application and browse to the example URL


(http://localhost:xxxx/HelloWorld/Welcome?name=Scott&numtimes=4). You can try
different values for name and numtimes in the URL. The ASP.NET MVC model binding
system automatically maps the named parameters from the query string in the address
bar to parameters in your method.like the bellow image:

Model view controller in .NET


Let's Start to learn MVC(Model view controller):

The first and very important thing to learn anything - what is this? So,here a question
occurs What is MVC? Reguraly we work with ASP.Net, a development framework to
develop websites or web pages using javascript, css etc. ASP.Net supports three different
type of development models -MVC is one of them, other two are web pages & web forms.

So, here now we can say:

1. MVC is an Asp.net programming Model.


2. MVC is a framework for building web applications.

MVC involves its own design which is called MVC design, stands for Model View Controller

1. Models represent the part of the application that handles the logic for the
application data. Often model objects retrieve data (and store data) from a
database.

2. View represents the parts of the application that handles the display of the data.
Most often the views are created from the model data.

3. Controller represents the part of the application that handles user interaction.
Typically controllers read data from a view, control user input, and send input data
to the mode

Here, now we can say that, The MVC model defines web applications with 3 logic layers:

1. The business layer (Model logic)

2. The display layer (View logic)

3. The input control (Controller logic)

The MVC separation helps you manage complex applications, because you can focus on
one aspect a time. For example, you can focus on the view without depending on the
business logic. It also makes it easier to test an application.
The MVC separation also simplifies group development. Different developers can work on
the view, the controller logic, and the business logic in parallel.

System Requirements:

So, Now to start work on your first MVC application you need to check some system
requirements as:

Have nothing? This button will install everything for you, including Visual Studio
2012 & MVC 4.

Have Visual Studio 2010? Install MVC 4 using the Web Platform Installer or the
standalone installer.

Using Visual Studio 2010 and looking for ASP.NET MVC 3? Here's the standalone
installer.

Or you can install Visual Web developer Visual Web Developer is a development
tool tailor made for MVC (and Web Forms).

Entity Framework CRUD Operations Using


Stored Procedure
In this article I would like to share something regarding Entity Framework, how we can
implement CRUD operations using Stored Procedures in Entity Framework.

In this explanation there are two ways of implementing CRUD operations:

1. By calling Stored Procedures using ExecuteStoreCommand and


ExecuteStoreQuery, without mapping to the Model

2. By mapping Stored Procedures to the Model.

OK first we will see how we can map the Stored Procedures to the Model to implement
CRUD operations.

Create an Empty web application from your VS2010; see:

First let us create a sample table, since I do not have SQL Server installed in my machine,
I am adding a SQL Server Database as in the following:
Here you can use the name Database1.mdf depending on your naming convention. Now
in the Server Explorer you will see your database, we will add a table and some Stored
Procedures here as follows:
Add the required columns and save the table with a desired name, the most important
aspect before you start working on Entity Framework is to have a Primary key in your
table.

Now my table looks as in the following on which we are going to perform CRUD
operations.

Ok now let's create Stored Procedures for Insert, Update, Delete and Select operations.

Insert Stored Procedure

CreatePROCEDURE dbo.InsertEmployee
(
@ID int,
@EmpName varchar(50),
@EmpAddress varchar(50)
)
AS
Begin
insert into
Employee(EmpID,Emp_Name,Emp_Address)values(@ID,@EmpName,@EmpAddress)
END

Delete Stored Procedure

Create PROCEDURE dbo.deleteEmp


(
@ID int
)
As
Begin
delete from Employee where EmpID=@ID
End

Select

Create PROCEDURE dbo.SelectEmployee


As
Begin
select * from Employee
End

Update

Create PROCEDURE dbo.UpdateEmployee


(@ID int,
@EmpName varchar(50),
@EmpAddress varchar(50))
As
Begin
update Employee set Emp_Name=@EmpName,Emp_Address=@EmpAddress where
EmpID=@ID
End

We are finished with our database. Now let us create a sample page and add an Entity
Model to our application.

Adding an Entity Model to your application:

After adding a Model you will immediately have this Entity Data Model Wizard where you
have to select Generate from the database and click on Next:
Select New Connection from the Choose your data:
Here on the Data Source you will have various sources which you will see by clicking on
Change, as I have created my database in my application I will use Microsoft SQL Server
Database File (SqlClient), if anyone is using SQL Server you can change that to SQL
Server from the options available.

Since I am using a Microsoft SQL Server Database File (SqlClient) I will browse for my
Database file and click on "OK".
Here you will see my Database file and also the connection settings in Web.Config will be
saved with the name EntitySampleEntities. Click Next where you will find all your tables
and Stored Procedures that you have created. Select the required one. Since I created
only one table and 4 Stored Procedures I will select them.

Initial Window
Click on "Finish" after you are finished, then you will see your model with the tables you
added and if there are any relations it will also map them. As of now I created just one
table that will be shown as follows:
Now we are finished with creating the database and adding it to an Entity Model. Now we
will see how to perform CRUD operations without mapping the Stored Procedures to the
model.

I also included some LINQ queries whereever needed, for example to auto-generate
Employee ID and binding the drop-down list.

Create a web page and add the following design to that page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="crud.aspx.cs"


Inherits="CRUDentity.crud" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h3>
Display data in gridview using Entity Framework with out Mapping Stored
Procedure
to Model
</h3>
<div style="width: 800px; margin: 0 auto; float: left;">
<asp:GridView ID="grdEmployess" runat="server" BackColor="White"
BorderColor="#999999"
DataKeyNames="EmpID" BorderStyle="None" BorderWidth="1px"
CellPadding="3" GridLines="Vertical">
<AlternatingRowStyle BackColor="#DCDCDC" />
<EmptyDataTemplate>
No record to show
</EmptyDataTemplate>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White"
/>
<PagerStyle BackColor="#999999" ForeColor="Black"
HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True"
ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
</div>
<br />
<div style="width: 800px; margin: 0 auto; float: left;">
<h3>
Insert Data to table using Entity Framework with out Mapping Stored
Procedures to
Model</h3>
<table>
<tr>
<td>
Employee ID :
</td>
<td>
<asp:TextBox ID="txtEmpID" ReadOnly="true"
runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Employee Name :
</td>
<td>
<asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqrdEmployeeName" runat="server"
ErrorMessage="*"
ControlToValidate="txtEmployeeName" ToolTip="Employee name
required" ValidationGroup="g"
Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Employee Address :
</td>
<td>
<asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqrdAddress" runat="server"
ErrorMessage="*" ControlToValidate="txtAddress"
ToolTip="Address required" ValidationGroup="g" Display="Dynamic"
ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr align="center">
<td colspan="3">
<asp:Button ID="btnInsert" runat="server" Text="Insert"
ValidationGroup="g" OnClick="btnInsert_Click" />
</td>
</tr>
</table>
</div>
<br />
<div style="width: 800px; margin: 0 auto; float: left;">
<h3>
Edit and Update data using storedprocedure With out mapping it to
Model</h3>
<table>
<tr>
<td>
Select Employee ID :
</td>
<td>
<asp:DropDownList ID="ddleditEmpID" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="ddleditEmpID_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
Employee Name :
</td>
<td>
<asp:TextBox ID="txtedtEmployeeName"
runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqrdedtEmpName" runat="server"
ErrorMessage="*" ControlToValidate="txtedtEmployeeName"
ToolTip="Employee name required" ValidationGroup="g1"
Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Employee Address :
</td>
<td>
<asp:TextBox ID="txtedtEmpAddress" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqrdedtEmpAddress" runat="server"
ErrorMessage="*"
ControlToValidate="txtedtEmpAddress" ToolTip="Address required"
ValidationGroup="g1"
Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr align="center">
<td colspan="4">
<asp:Button ID="btnUpdate" runat="server" Text="Update"
OnClick="btnUpdate_Click" />
</td>
</tr>
</table>
</div>
<br />
<div style="width: 800px; margin: 0 auto; float: left;">
<h3>
Delete data using storedprocedure With out mapping it to Model</h3>
<table>
<tr>
<td>
Select Employee ID to Delete :
</td>
<td>
<asp:DropDownList ID="ddlEmpID" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr align="center">
<td colspan="2">
<asp:Button ID="btnDelete" runat="server" ValidationGroup="g1"
Text="Delete" OnClick="btnDelete_Click" />
</td>
</tr>
</table>
</div>
</center>
</div>
</form>
</body>
</html>

Yourpage.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace CRUDentity
{
public partial class crud : System.Web.UI.Page
{
EntitySampleEntities entities = new EntitySampleEntities();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
checkMax();
loadGrid();
bindDDL();
}
}

protected void btnInsert_Click(object sender, EventArgs e)


{
Page.Validate("g");
if (Page.IsValid)
{
var ietsParameterID = new SqlParameter("@ID", System.Data.SqlDbType.Int);
ietsParameterID.Value = Convert.ToInt16(txtEmpID.Text);
var ietsParameterEmpName = new SqlParameter("@EmpName",
txtEmployeeName.Text);
var ietsParameterEmpAddress = new SqlParameter("@EmpAddress",
txtAddress.Text);

entities.ExecuteStoreCommand("InsertEmployee
@ID,@EmpName,@EmpAddress", ietsParameterID, ietsParameterEmpName,
ietsParameterEmpAddress);
loadGrid();
checkMax();
bindDDL();
txtAddress.Text = string.Empty;
txtEmployeeName.Text = string.Empty;
}
}

public void checkMax()


{
int? maxEmpID = entities.Employees.Max(q => (int?)q.EmpID);

if (maxEmpID != null)
{
maxEmpID = maxEmpID + 1;
txtEmpID.Text = maxEmpID.ToString();
}
else
{
maxEmpID = 1000;
txtEmpID.Text = maxEmpID.ToString();
}
}

public void loadGrid()


{
var selectData =
entities.ExecuteStoreQuery<Employee>("SelectEmployee").ToList();
grdEmployess.DataSource = selectData;
grdEmployess.DataBind();
}

public void bindDDL()


{
var display = from e in entities.Employees select new { e.EmpID };

ddlEmpID.DataSource = display.ToList();
ddlEmpID.DataTextField = "EmpID";
ddlEmpID.DataValueField = "EmpID";
ddlEmpID.DataBind();
ddlEmpID.Items.Insert(0, "--Select--");

ddleditEmpID.DataSource = display.ToList();
ddleditEmpID.DataTextField = "EmpID";
ddleditEmpID.DataValueField = "EmpID";
ddleditEmpID.DataBind();
ddleditEmpID.Items.Insert(0, "--Select--");
}

protected void btnDelete_Click(object sender, EventArgs e)


{
if (ddlEmpID.SelectedItem.Text != "--Select--")
{
var ietsParameterID = new SqlParameter("@ID", ddlEmpID.SelectedItem.Text);
entities.ExecuteStoreCommand("deleteEmp @ID", ietsParameterID);
loadGrid();
checkMax();
bindDDL();
}
}

protected void btnUpdate_Click(object sender, EventArgs e)


{
Page.Validate("g1");
if (Page.IsValid)
{
if (ddleditEmpID.SelectedItem.Text != "--Select--")
{
var ietsParameterID = new SqlParameter("@ID",
System.Data.SqlDbType.Int);
ietsParameterID.Value = Convert.ToInt16(ddleditEmpID.SelectedItem.Text);
var ietsParameterEmpName = new SqlParameter("@EmpName",
txtedtEmployeeName.Text);
var ietsParameterEmpAddress = new SqlParameter("@EmpAddress",
txtedtEmpAddress.Text);

entities.ExecuteStoreCommand("UpdateEmployee
@ID,@EmpName,@EmpAddress", ietsParameterID, ietsParameterEmpName,
ietsParameterEmpAddress);
loadGrid();
}
}
}

protected void ddleditEmpID_SelectedIndexChanged(object sender, EventArgs e)


{
if (ddleditEmpID.SelectedItem.Text != "--Select--")
{
int id = Convert.ToInt16(ddleditEmpID.SelectedValue.ToString());
var display = from e1 in entities.Employees
where e1.EmpID.Equals(id)
select new { e1.Emp_Name, e1.Emp_Address };

foreach (var v in display)


{
txtedtEmployeeName.Text = v.Emp_Name;
txtedtEmpAddress.Text = v.Emp_Address;
}
}
}
}
}

Sample screen shots


When you first run the application:

Since there are no records in the table you will see the grid view is empty. Also you will
see the Employee ID is read only, to avoid duplicates I make this one if you want you can
remove that and do whatever you need to.

Now we will see what happens after submitting data:


Now we will edit the record see here I will change the Employee Address initially it is
Hyderabad I will change it to some other. To do that select the Employee ID that you
need to edit and update. Since here I have only one Employee I will do for that.

Before editing Employee Address

Let's do the deleting; for this I will add another employee to the table as shown and then
will delete it.

Before delete
After Delete

That's it, this is how we can do basic CRUD operations using Entity Framework without
mapping Stored Procedures to the Model.
Master Detail CRUD Operations Using
ASP.Net MVC 3 And Entity Framework
In this article I discuss how we can perform Master-Detail CRUD operation using Entity
Framework (Code First) and ASP.Net MVC 3. Here I have used JSON (json2.js) for data
passing, Ajax for posting and DataTables (datatables.js) for manipulating detail records.

Fig 1: Creating New Sales Record with multiple sales Sub Record

Creating Master Detail CRUD Application: Create Sample Solution

Open VS 2010

Create ASP.Net MVC 3 Project named "MasterDetail"

Here I have used

JSON for passing data view to controller.

Data Tables for manipulating details record.

Let us add JSON and DataTables js file to our project in the following way.

Select Add Library Package Reference by right-clicking Reference.


The Add Library Package Manager Window will appear; from the window search
json2 & DataTables and install them.
After installing them, you will find json2.js and datatables.js in the script folder.

Now our solution is ready for further work.

Creating Model
Here we have considered we have two entities SalesMain and SalesSub (a one to many
relation). One salesMain has multiple sales sub records.

public class SalesMain


{

[Key]
public int SalesId { get; set; }
public string ReferenceNo { get; set; }
public DateTime SalesDate { get; set; }
public string SalesPerson { get; set; }

public virtual ICollection<SalesSub> SalesSubs { get; set; }


}

public class SalesSub


{

[Key, Column(Order = 0)]


public int SalesId { get; set; }
[Key, Column(Order = 1)]
public string ItemName { get; set; }

public int Qty { get; set; }


public decimal UnitPrice { get; set; }

public virtual SalesMain SalesMain { get; set; }


}
Now build your project / press f5.

Creating Controller, Context and Views

Right-click on the controller folder and select Add >> Controller

Name it SalesController

Select "SalesMain (MasterDetail.Models)" as a Model Class

Select <new data Context> and give its name


"MasterDetail.Models.MasterDetailContext"
Then automatically it will create Views, Controller and Context Class.

Now we have to modify Our Sales Controller Class and Views.


Modify Sales Controller
Modify the existing Create method by the following:

[HttpPost]
public JsonResult Create(SalesMain salesmain)
{
try
{
if (ModelState.IsValid)
{

// If sales main has SalesID then we can understand we have existing


sales Information
// So we need to Perform Update Operation

// Perform Update
if (salesmain.SalesId > 0)
{

var CurrentsalesSUb = db.SalesSubs.Where(p => p.SalesId ==


salesmain.SalesId);

foreach (SalesSub ss in CurrentsalesSUb)


db.SalesSubs.Remove(ss);

foreach (SalesSub ss in salesmain.SalesSubs)


db.SalesSubs.Add(ss);

db.Entry(salesmain).State = EntityState.Modified;
}
//Perform Save
else
{
db.SalesMains.Add(salesmain);
}

db.SaveChanges();
// If Sucess== 1 then Save/Update Successfull else there it has Exception
return Json(new { Success = 1, SalesID = salesmain.SalesId, ex="" });
}
}
catch (Exception ex)
{
// If Sucess== 0 then Unable to perform Save/Update Operation and send
Exception to View as JSON
return Json(new { Success = 0, ex = ex.Message.ToString() });
}

return Json(new { Success = 0, ex = new Exception("Unable to


save").Message.ToString() });
}

Modify the Edit method in the following way:

public ActionResult Edit(int id)


{
ViewBag.Title = "Edit";
SalesMain salesmain = db.SalesMains.Find(id);

//Call Create View


return View("Create", salesmain);
}

Delete the "Edit method" with Http post because we will use a Create method for
performing a Save and Update operation.

Finally the sales controller looks like the following.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MasterDetail.Models;
using System.Web.Helpers;
using System.Data.Objects;

namespace MasterDetail.Controllers
{
public class SalesController : Controller
{
private MasterDetailContext db = new MasterDetailContext();
//
// GET: /Sales/
public ViewResult Index()
{
return View(db.SalesMains.ToList());
}

//
// GET: /Sales/Details/5

public ViewResult Details(int id)


{
SalesMain salesmain = db.SalesMains.Find(id);
return View(salesmain);
}

//
// GET: /Sales/Create

public ActionResult Create()


{
ViewBag.Title = "Create";
return View();
}

// POST: /Sales/Create
/// <summary>
/// This method is used for Creating and Updating Sales Information
/// (Sales Contains: 1.SalesMain and *SalesSub )
/// </summary>
/// <param name="salesmain">
/// </param>
/// <returns>
/// Returns Json data Containing Success Status, New Sales ID and Exeception
/// </returns>
[HttpPost]
public JsonResult Create(SalesMain salesmain)
{
try
{
if (ModelState.IsValid)
{

// If sales main has SalesID then we can understand we have existing


sales Information
// So we need to Perform Update Operation

// Perform Update
if (salesmain.SalesId > 0)
{

var CurrentsalesSUb = db.SalesSubs.Where(p => p.SalesId ==


salesmain.SalesId);

foreach (SalesSub ss in CurrentsalesSUb)


db.SalesSubs.Remove(ss);

foreach (SalesSub ss in salesmain.SalesSubs)


db.SalesSubs.Add(ss);

db.Entry(salesmain).State = EntityState.Modified;
}
//Perform Save
else
{
db.SalesMains.Add(salesmain);
}

db.SaveChanges();

// If Sucess== 1 then Save/Update Successfull else there it has Exception


return Json(new { Success = 1, SalesID = salesmain.SalesId, ex="" });
}
}
catch (Exception ex)
{
// If Sucess== 0 then Unable to perform Save/Update Operation and send
Exception to View as JSON
return Json(new { Success = 0, ex = ex.Message.ToString() });
}

return Json(new { Success = 0, ex = new Exception("Unable to


save").Message.ToString() });
}

//
// GET: /Sales/Edit/5
public ActionResult Edit(int id)
{
ViewBag.Title = "Edit";
SalesMain salesmain = db.SalesMains.Find(id);

//Call Create View


return View("Create", salesmain);
}

// GET: /Sales/Delete/5
public ActionResult Delete(int id)
{
SalesMain salesmain = db.SalesMains.Find(id);
return View(salesmain);
}

// POST: /Sales/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
SalesMain salesmain = db.SalesMains.Find(id);
db.SalesMains.Remove(salesmain);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
Modifying Create View
Add the following *.js and *.css file.

@*This is for jquery*@


<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
@*This is for jquery UI, for Calender control*@
<script src="../../Scripts/jquery-ui-1.8.11.js" type="text/javascript"></script>

@*This is for JSON*@


<script src="../../Scripts/json2.js" type="text/javascript"></script>

@*These are for DataTables*@


<script src="../../Scripts/DataTables-1.8.1/media/js/jquery.dataTables.js"
type="text/javascript"></script>
<script src="../../Scripts/DataTables-1.8.1/extras/TableTools/media/js/TableTools.js"
type="text/javascript"></script>
<script src="../../Scripts/DataTables-1.8.1/extras/TableTools/media/js/ZeroClipboard.js"
type="text/javascript"></script>

@*These are for styling Control*@


<link href="../../Content/DataTables-1.8.1/extras/TableTools/media/css/TableTools.css"
rel="stylesheet" type="text/css" />
<link href="../../Content/DataTables-
1.8.1/extras/TableTools/media/css/TableTools_JUI.css" rel="stylesheet" type="text/css"
/>
<link href="../../Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css"
/>
Add HTML table for manipulating list of data
After adding a HTML table, we have converted it to a DataTable so that we can easily
add/delete an item and read an item more easily.

<table class="tbl" id="tbl">


<thead>
<tr>
<th>ItemName</th> <th>Quantity</th><th>Unit Price</th>
</tr>
</thead>

<tbody>
@if (Model != null)
{
foreach (var item in Model.SalesSubs)
{
<tr>
<td>
@Html.DisplayTextFor(i => item.ItemName)
</td>
<td>
@Html.DisplayTextFor(i => item.Qty)
</td>
<td>
@Html.DisplayTextFor(i => item.UnitPrice)
</td>

</tr>
}
}

</tbody>

</table>

This is a simple HTML table; then we used the following jQuery for converting it to a
DataTable.

$(document).ready(function () {

// here i have used datatables.js (jQuery Data Table)


$('.tbl').dataTable({
"sDom": 'T<"clear">lfrtip',
"oTableTools": {
"aButtons": [],
"sRowSelect": "single"
},
"bLengthChange": false,
"bFilter": false,
"bSort": false,
"bInfo": false
});

var oTable = $('.tbl').dataTable();


});
Adding new row to Table
The following code shows how to read from text boxes and then add them to a
DataTable.

function Add() {
// Adding item to table
$('.tbl').dataTable().fnAddData([$('#ItemName').val(), $('#Qty').val(), $
('#UnitPrice').val()]);

// Making Editable text empty


$('#ItemName').val("")
$('#Qty').val("")
$('#UnitPrice').val("")

}
Delete selected row from Table
Following code shows how to remove a selected item from a DataTable.

// This function is used fro


// delete selected row from Detail Table|
// set deleted item to Edit text Boxes
function DeleteRow() {

// Here I have used DataTables.TableTools plugin for getting selected row items
var oTT = TableTools.fnGetInstance('tbl'); // Get Table instance
var sRow = oTT.fnGetSelected(); // Get Selected Item From Table

// Set deleted row item to editable text boxes


$('#ItemName').val($.trim(sRow[0].cells[0].innerHTML.toString()));
$('#Qty').val(jQuery.trim(sRow[0].cells[1].innerHTML.toString()));
$('#UnitPrice').val($.trim(sRow[0].cells[2].innerHTML.toString()));

$('.tbl').dataTable().fnDeleteRow(sRow[0]);

}
Save/Posting Data to sales Controller

Here we have two steps:

1. Read view data and create JSON object

2. Ajax post

function Sales_save() {
// Step 1: Read View Data and Create JSON Object

// Creating SalesSub Json Object


var salessub = {"SalesId":"", "ItemName":"","Qty":"","UnitPrice":""};

// Creating SalesMain Json Object


var salesmain = { "SalesId":"","ReferenceNo": "", "SalesDate": "", "SalesPerson":
"", "SalesSubs":[] };

// Set Sales Main Value


salesmain.SalesId = $("#SalesId").val();
salesmain.ReferenceNo = $("#ReferenceNo").val();
salesmain.SalesDate = $("#SalesDate").val();
salesmain.SalesPerson = $("#SalesPerson").val();

// Getting Table Data from where we will fetch Sales Sub Record
var oTable = $('.tbl').dataTable().fnGetData();

for (var i = 0; i < oTable.length; i++)


{

// IF This view is for edit then it will read SalesId from Hidden field
if ($('h2').text() == "Edit")
{
salessub.SalesId = $('#SalesId').val();
}
else
{
salessub.SalesId = 0;
}

// Set SalesSub individual Value


salessub.ItemName = oTable[i][0];
salessub.Qty = oTable[i][1];
salessub.UnitPrice = oTable[i][2];
// adding to SalesMain.SalesSub List Item
salesmain.SalesSubs.push(salessub);
salessub = { "ItemName": "", "Qty": "", "UnitPrice": "" };

}
// Step 1: Ends Here

// Set 2: Ajax Post


// Here i have used ajax post for saving/updating information
$.ajax({
url: '/Sales/Create',
data: JSON.stringify(salesmain),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {

if (result.Success == "1") {
window.location.href = "/Sales/index";
}
else {
alert(result.ex);
}
}
});

S-ar putea să vă placă și