Documente Academic
Documente Profesional
Documente Cultură
Net MVC
How to add custom validators in mvc4?
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 just run your project and add sample/Index in your browser url after
localhost.
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.
[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.
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.
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.
3. Auto-generated Model
Now
That's it.
If your database table structure is the same then only change the connection string in
the web.config
This procedure takes one input parameter @MerchantID and returns the Name and
Address of the respective merchant id.
You can select the procedure at the time of creation of the entity model.
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
So now call the auto-generated procedure function and execute the Stored Procedure.
The difference between complex type functions and entity type functions to execute a
procedure.
The following is the auto-generated code of the entity type and complex type:
Paging in Entity Framework
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. }
Just mention the current column Name, order by state, page number, page size and
entity to return the current page record with sort.
create a normal Stored Procedure so we can execute that Stored Procedure in the
following scenarios.
Stored Procedure
The Stored Procedure is now created and I assume you understand all the basics of the
Entity Framework.
The following is another way to execute a SQL query without calling entity
functions:
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.
Note: Before running the source code please change the web.config connection string.
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.
Application Templates
There are several templates available in ASP.NET MVC 4 development work. These
templates are as follows:
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.
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.
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 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.
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.
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
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.
2. Add a new WCF Service Application and give it the name FileHandling.WCFHost.
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.
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. }
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:
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.
Also note that for Security mode has been set to TransportCredentialsOnly and the
ClientCredentialType has been set to Windows.
Client
FileUpload
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
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:
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.
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
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 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.
You can create file system of your choice but you have to map with IIS server. We map
with the help of Virtual Directory.
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
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.
Steps Involved:
Create a WCF Service:
The following steps should be followed to create a WCF service using Visual Studio 2010.
iii. Select WCF Service Application under installed template category WCF and name it as
Wcf.
v. Click OK.
vii. Right click the Solution Explorer and add a New Item.
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();
}
}
namespace Wcf
{
public class CustomService : ICustomService
{
public string GetTime()
{
return DateTime.Now.ToString();
}
}
}
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.
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.
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.)
Introduction on IIS 7
Step 1: From Visual Studio 2005 or above, publish your web application.
"C:\intepub\wwwroot\YourVirtualDir" folder.
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.
Start -> Control Panel -> Add Remove Programs -> Add/Removes Windows
Components.
Copy and paste your web site folder into the wwwroot folder.
Step 4: After pasting your folder is set on the default web site.
Manage -> Computer management (Local) -> Internet Information Service -> Website
-> Default Web Site.
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.
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.
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.
1. When the Anonymous User option is checked then everyone is given access to a
web page and it overrides all authentication settings.
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 .
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 .
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.
Click on right click on the IIS Express and say show all applications .
Step 1: From Visual Studio 2005 or above, publish your web application.
"C:\intepub\wwwroot\YourVirtualDir" folder.
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.
Introduction Here
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.
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.
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.
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/
//
// GET: /Home/Details/5
//
// GET: /Home/Create
//
// 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
//
// 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();
}
}
}
}
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.
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)
<h2>Index</h2>
<table>
<tr>
<th></th>
<th>
Id
</th>
<th>
FirstName
</th>
<th>
LastName
</th>
<th>
Phone
</th>
<th>
Email
</th>
</tr>
<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.
If you see at Controller\HomeController.cs, for creating new contacts you will find
code below.
// GET: /Home/Create
//
// 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
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.
//
// 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
<h2>Create</h2>
<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>
If you see at Controller\HomeController.cs , for editing contacts you will find code
below.
// GET: /Home/Edit/5
//
// 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();
}
}
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).
Controller\HomeController.cs
// GET: /Home/Edit/5
//
// 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();
}
}
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
[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.
Index.aspx
<h2>Index</h2>
<table>
<tr>
<th></th>
<th>
Id
</th>
<th>
FirstName
</th>
<th>
LastName
</th>
<th>
Phone
</th>
<th>
Email
</th>
</tr>
<% } %>
</table>
<p>
<%= Html.ActionLink("Create New", "Create") %>
</p>
</asp:Content>
<div id="title">
<h1>C# Corner Author's Contact Details</h1>
</div>
This article explained about, how to perform CRUD operation on a table in ASP.Net MVC
Framework.
using System.Web;
using System.Web.Mvc;
namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/
//
// GET: /HelloWorld/Welcome/
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.
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.
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:
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).
OK first we will see how we can map the Stored Procedures to the Model to implement
CRUD operations.
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.
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
Select
Update
We are finished with our database. Now let us create a sample page and add an Entity
Model to our 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:
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();
}
}
entities.ExecuteStoreCommand("InsertEmployee
@ID,@EmpName,@EmpAddress", ietsParameterID, ietsParameterEmpName,
ietsParameterEmpAddress);
loadGrid();
checkMax();
bindDDL();
txtAddress.Text = string.Empty;
txtEmployeeName.Text = string.Empty;
}
}
if (maxEmpID != null)
{
maxEmpID = maxEmpID + 1;
txtEmpID.Text = maxEmpID.ToString();
}
else
{
maxEmpID = 1000;
txtEmpID.Text = maxEmpID.ToString();
}
}
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--");
}
entities.ExecuteStoreCommand("UpdateEmployee
@ID,@EmpName,@EmpAddress", ietsParameterID, ietsParameterEmpName,
ietsParameterEmpAddress);
loadGrid();
}
}
}
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.
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
Open VS 2010
Let us add JSON and DataTables js file to our project in the following way.
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.
[Key]
public int SalesId { get; set; }
public string ReferenceNo { get; set; }
public DateTime SalesDate { get; set; }
public string SalesPerson { get; set; }
Name it SalesController
[HttpPost]
public JsonResult Create(SalesMain salesmain)
{
try
{
if (ModelState.IsValid)
{
// Perform Update
if (salesmain.SalesId > 0)
{
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() });
}
Delete the "Edit method" with Http post because we will use a Create method for
performing a Save and Update operation.
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
//
// GET: /Sales/Create
// 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)
{
// Perform Update
if (salesmain.SalesId > 0)
{
db.Entry(salesmain).State = EntityState.Modified;
}
//Perform Save
else
{
db.SalesMains.Add(salesmain);
}
db.SaveChanges();
//
// GET: /Sales/Edit/5
public ActionResult Edit(int id)
{
ViewBag.Title = "Edit";
SalesMain salesmain = db.SalesMains.Find(id);
// 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.
<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 () {
function Add() {
// Adding item to table
$('.tbl').dataTable().fnAddData([$('#ItemName').val(), $('#Qty').val(), $
('#UnitPrice').val()]);
}
Delete selected row from Table
Following code shows how to remove a selected item from a DataTable.
// 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
$('.tbl').dataTable().fnDeleteRow(sRow[0]);
}
Save/Posting Data to sales Controller
2. Ajax post
function Sales_save() {
// Step 1: Read View Data and Create JSON Object
// Getting Table Data from where we will fetch Sales Sub Record
var oTable = $('.tbl').dataTable().fnGetData();
// 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;
}
}
// Step 1: Ends Here
if (result.Success == "1") {
window.location.href = "/Sales/index";
}
else {
alert(result.ex);
}
}
});