Creating Insert Update and Delete Application In MVC 4 Using Razor

Creating an insert, update and delete application in MVC 4 using Razor syntax. I am providing a small demo application.

Server Part

Starting with creating the table: tbInsertMobile.

Creating Table

  1. Create table tbInsertMobile  
  2. (  
  3. MobileID Bigint not null primary key IDENTITY(1,1),  
  4. MobileName Nvarchar(100),  
  5. MobileIMEno Nvarchar(50),  
  6. mobileprice numeric(19,2),  
  7. mobileManufacured Nvarchar(100),  
  8. CreatedDate datetime default Getdate()  
  9. )

Creating Stored Procedures

  1. Create proc Usp_InsertUpdateDelete  
  2. @MobileID Bigint =0 ,  
  3. @MobileName Nvarchar(100) = null,  
  4. @MobileIMEno Nvarchar(50) = null,  
  5. @mobileprice numeric(19,2) = 0,  
  6. @mobileManufacured Nvarchar(100) = null,  
  7. @Query int  
  8. as   
  9. begin  
  10. if(@Query = 1)  
  11. begin  
  12. Insert into  tbInsertMobile  
  13. (  
  14. MobileName ,  
  15. MobileIMEno ,  
  16. mobileprice,  
  17. mobileManufacured  
  18. )  
  19. values  
  20. (  
  21. @MobileName ,  
  22. @MobileIMEno ,  
  23. @mobileprice,  
  24. @mobileManufacured  
  25. )  
  26. if(@@ROWCOUNT > 0)  
  27. begin  
  28. select 'Insert'  
  29. end  
  30. end  
  31. if(@Query = 2)  
  32. begin  
  33. update tbInsertMobile  
  34. set  
  35. MobileName =@MobileName ,  
  36. MobileIMEno =@MobileIMEno ,  
  37. mobileprice =@mobileprice,  
  38. mobileManufacured =@mobileManufacured  
  39. where tbInsertMobile.MobileID =@MobileID  
  40. select 'Update'  
  41. end  
  42. if(@Query = 3)  
  43. begin  
  44. Delete from tbInsertMobile where tbInsertMobile.MobileID =@MobileID  
  45. select 'Deleted'  
  46. end  
  47. if(@Query = 4)  
  48. begin  
  49. Select * from tbInsertMobile  
  50. end  
  51. End  
  52. if(@Query = 5)  
  53. begin  
  54. Select * from tbInsertMobile where tbInsertMobile.MobileID =@MobileID  
  55. end  
Now for the code.

Begin by creating a MVC application as in the following:


After adding an application name the second screen will pop up prompting for a selection of a Project Template.
 

In this select Internet application and View Engine Razor and click OK.

Then your project is created successfully.
 

In this application I will first add a Model.
 

Provide the Model the name Mobiledata.cs.
 

After creating the model:
 

In the Model I will declare Properties and Validation (DataAnnotations).
 

Here are a number of DataAnnotations that we can use in a model.

The following are the Data Annotations we can use in a Model:
  1. DisplayName: Provides a general-purpose attribute that lets you specify localizable strings to display.
  2. Required: A value is required
  3. DataType: The data type annotation can be used to specify the data type for validation.
  4. StringLength: Max. length of an array or string data allowed.
  5. DisplayFormat: Specify the display format for a property like various formats for the Date property.
  6. ReqularExpression: Validate the value of a property by specifyng a regular expression pattern.
  7. Range: Numeric range constraints for the data field value.
  8. MaxLength: Specify max length for a string property.
  9. Bind: Specify fields to include or exclude when adding parameter or form values to model properties.
  10. Compare: The Compares property compares two properties
  11. Key: Denotes one or more properties that uniquely identify an entity.

In the Model I added Properties and Validation.

Model Code

  1. using System.ComponentModel.DataAnnotations;  
  2. namespace MymobilewalaMvc.Models  
  3. {  
  4.     public class Mobiledata  
  5.     {  
  6.         public int MobileID {get;set;}  
  7.         [Required(ErrorMessage="Please Enter Mobile Name")]  
  8.         [Display(Name="Enter Mobile Name")]  
  9.         [StringLength(50, MinimumLength = 3, ErrorMessage = "Mobile Name must be between 3 and 50 characters!")]  
  10.         public string MobileName {get;set;}  
  11.         [Required(ErrorMessage="Please Enter MobileIMEno")]  
  12.         [Display (Name="Enter MobileIMEno")]  
  13.         [MaxLength (100,ErrorMessage="Exceeding Limit")]  
  14.         public string MobileIMEno {get;set;}  
  15.         [Required(ErrorMessage = "Please Enter Mobile Price")]  
  16.         [Display (Name="Enter Mobile Price")]  
  17.         [DataType(DataType.Currency)]  
  18.         public string mobileprice {get;set;}  
  19.         [Required(ErrorMessage = "Please Enter Mobile Manufacured")]  
  20.         [Display(Name = "Enter Mobile Manufacured")]  
  21.         [DataType(DataType.Text)]  
  22.         public string mobileManufacured { getset; }  
  23.     }  
  24. }  
We have completed creating the Model. Let's start adding the controller.
 

Select Controller; a new Window will then pop up asking for the Controller name.
 

Provide the name MobilestoreController. (We should add "Controller" as a suffix of all Controllers.)

And click on the Add button to add it.

If you do not understand what a controller is then see my first tutorial.

Now we will add a folder and class for accessing a Database Connection and doing the inserting, updating and deleting.

The following shows the added folder name DataAccessLayer.
 

Right-click on the DataAccessLayer folder and select add class then provide the class the name DBdata.cs.
 

Namespace used.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data;  
  6. using System.Data.SqlClient;  
  7. using System.Configuration;  
  8. using MymobilewalaMvc.Models;  
The namespace MymobilewalaMvc.Models is used to access the model we created.

In the Model I have created the following 5 methods:

  1.  InsertData
  2. UpdateData
  3. DeleteData
  4. SelectAllData
  5. SelectAllDatabyID

InsertData

  1. public string InsertData(Mobiledata MD)  
  2. {  
  3.     SqlConnection con = null;  
  4.     string result = "";  
  5.     try  
  6.     {  
  7.         con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString());  
  8.         SqlCommand cmd = new SqlCommand("Usp_InsertUpdateDelete", con);  
  9.         cmd.CommandType = CommandType.StoredProcedure;  
  10.         cmd.Parameters.AddWithValue("@MobileID", 0);  
  11.         // i will pass zero to MobileID beacause its Primary .  
  12.         cmd.Parameters.AddWithValue("@MobileName", MD.MobileName);  
  13.         cmd.Parameters.AddWithValue("@MobileIMEno", MD.MobileIMEno);  
  14.         cmd.Parameters.AddWithValue("@mobileprice", MD.mobileprice);  
  15.         cmd.Parameters.AddWithValue("@mobileManufacured", MD.mobileManufacured);  
  16.         cmd.Parameters.AddWithValue("@Query", 1);  
  17.         con.Open();  
  18.         result = cmd.ExecuteScalar().ToString();  
  19.         return result;  
  20.     }  
  21.     catch  
  22.     {  
  23.         return result = "";  
  24.     }  
  25.     finally  
  26.     {  
  27.         con.Close();  
  28.     }  
  29. }  
Update Data
  1. public string UpdateData(Mobiledata MD)  
  2. {  
  3.     SqlConnection con = null;  
  4.     string result = "";  
  5.     try  
  6.     {  
  7.         con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString());  
  8.         SqlCommand cmd = new SqlCommand("Usp_InsertUpdateDelete", con);  
  9.         cmd.CommandType = CommandType.StoredProcedure;  
  10.         cmd.Parameters.AddWithValue("@MobileID", MD.MobileID);  
  11.         cmd.Parameters.AddWithValue("@MobileName", MD.MobileName);  
  12.         cmd.Parameters.AddWithValue("@MobileIMEno", MD.MobileIMEno);  
  13.         cmd.Parameters.AddWithValue("@mobileprice", MD.mobileprice);  
  14.         cmd.Parameters.AddWithValue("@mobileManufacured", MD.mobileManufacured);  
  15.         cmd.Parameters.AddWithValue("@Query", 2);  
  16.         con.Open();  
  17.         result = cmd.ExecuteScalar().ToString();  
  18.         return result;  
  19.     }  
  20.     catch  
  21.     {  
  22.         return result = "";  
  23.     }  
  24.     finally  
  25.     {  
  26.         con.Close();  
  27.     }  
  28. }  
Delete Data
  1. public string DeleteData(Mobiledata MD)  
  2. {  
  3.     SqlConnection con = null;  
  4.     string result = "";  
  5.     try  
  6.     {  
  7.         con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString());  
  8.         SqlCommand cmd = new SqlCommand("Usp_InsertUpdateDelete", con);  
  9.         cmd.CommandType = CommandType.StoredProcedure;  
  10.         cmd.Parameters.AddWithValue("@MobileID", MD.MobileID);  
  11.         cmd.Parameters.AddWithValue("@MobileName"null);  
  12.         cmd.Parameters.AddWithValue("@MobileIMEno"null);  
  13.         cmd.Parameters.AddWithValue("@mobileprice", 0);  
  14.         cmd.Parameters.AddWithValue("@mobileManufacured"null);  
  15.         cmd.Parameters.AddWithValue("@Query", 3);  
  16.         con.Open();  
  17.         result = cmd.ExecuteScalar().ToString();  
  18.         return result;  
  19.     }  
  20.     catch  
  21.     {  
  22.         return result = "";  
  23.     }  
  24.     finally  
  25.     {  
  26.         con.Close();  
  27.     }  
  28. }  
SelectAllData
  1. public DataSet SelectAllData()  
  2. {  
  3.     SqlConnection con = null;  
  4.     string result = "";  
  5.     DataSet ds = null;  
  6.     try  
  7.     {  
  8.         con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString());  
  9.         SqlCommand cmd = new SqlCommand("Usp_InsertUpdateDelete", con);  
  10.         cmd.CommandType = CommandType.StoredProcedure;  
  11.         cmd.Parameters.AddWithValue("@MobileID",0);  
  12.         cmd.Parameters.AddWithValue("@MobileName"null);  
  13.         cmd.Parameters.AddWithValue("@MobileIMEno"null);  
  14.         cmd.Parameters.AddWithValue("@mobileprice", 0);  
  15.         cmd.Parameters.AddWithValue("@mobileManufacured"null);  
  16.         cmd.Parameters.AddWithValue("@Query", 4);  
  17.         con.Open();  
  18.         SqlDataAdapter da = new SqlDataAdapter();  
  19.         da.SelectCommand = cmd;  
  20.         ds = new DataSet();   da.Fill(ds);  
  21.         return ds;  
  22.     }  
  23.     catch  
  24.     {  
  25.         return ds;  
  26.     }  
  27.     finally  
  28.     {  
  29.         con.Close();  
  30.     }  
  31. }  

SelectAllDatabyID

  1. public DataSet SelectAllDatabyID(string MobileID)  
  2. {  
  3.     SqlConnection con = null;  
  4.     string result = "";  
  5.     DataSet ds = null;  
  6.     try  
  7.     {  
  8.         con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString());  
  9.         SqlCommand cmd = new SqlCommand("Usp_InsertUpdateDelete", con);  
  10.         cmd.CommandType = CommandType.StoredProcedure;  
  11.         cmd.Parameters.AddWithValue("@MobileID", MobileID); // i will pass zero to MobileID beacause its Primary .  
  12.         cmd.Parameters.AddWithValue("@MobileName"null);  
  13.         cmd.Parameters.AddWithValue("@MobileIMEno"null);  
  14.         cmd.Parameters.AddWithValue("@mobileprice", 0);  
  15.         cmd.Parameters.AddWithValue("@mobileManufacured"null);  
  16.         cmd.Parameters.AddWithValue("@Query", 4);  
  17.         con.Open();  
  18.         SqlDataAdapter da = new SqlDataAdapter();  
  19.         da.SelectCommand = cmd;  
  20.         ds = new DataSet();  
  21.         da.Fill(ds);  
  22.         return ds;  
  23.      }  
  24.      catch  
  25.      {  
  26.         return ds;  
  27.     }  
  28.     finally  
  29.     {  
  30.         con.Close();  
  31.     }  
  32. }  
Ha ha, finally we have completed the Transcation Part.

Let's return to the Controller we added.


Just Rebuild the application.

In the Controller add the following two methods:
  1. public ActionResult InsertMobile() // Calling when we first hit controller.  
  2. {  
  3.    return View();  
  4. }  
  5. [HttpPost]  
  6. public ActionResult InsertMobile(Mobiledata MB) // Calling on http post (on Submit)  
  7. {  
  8.     return View();  
  9. }  
Now I will add a View to the Controller.

Just right-click on Action result Insertmobile add select "Add View...".


After selecting Add View we will get a New Window.

Just select (create a strongly-typed view).

Inside that select the Model Name we created and click Add.
 


After adding like this a View will be generated.

With extension .cshtml.
 

In the design we will use a HTMLHELPER Class.

To begin with form we use:
  1. @using (Html.BeginForm())  
  2. {   
  3. }  
For the Label, TextBox and validation message we use:
  1. @Html.LabelFor(a => a.MobileName)  
  2. @Html.TextBoxFor(a => a.MobileName)  
  3. @Html.ValidationMessageFor(a => a.MobileName)  
You will be thinking, what is "a"? It is a lamda expressiom.

The advantage of using a lamda expression is that you get compile-time checking of your properties. For example, if you rename ViewModel.Name to ViewModel.ClientName then all your Html.DisplayFor(x => model.Name) won't compile, thus making sure you change them. If you don't use lamda expressions then all your Html.Display() calls will work, but you will get hidden bugs with model binding that will not be immediately obvious of what's wrong.

The following is the complete design of InsertMobile.

  1. @model MymobilewalaMvc.Models.Mobiledata  
  2. @{  
  3.     ViewBag.Title = "InsertMobile";  
  4. }  
  5. <h2>  
  6.     InsertMobile</h2>  
  7. <table>  
  8.     <tr>  
  9.         <td>  
  10.             @Html.ActionLink("Show All Mobile List""ShowAllMobileDetails")  
  11.         </td>  
  12.     </tr>  
  13. </table>     
  14. @using (Html.BeginForm())  
  15. {   
  16.     <table width="100%">  
  17.         <tr>  
  18.             <td>  
  19.                 @Html.LabelFor(a => a.MobileName)  
  20.             </td>  
  21.         </tr>  
  22.         <tr>  
  23.             <td>  
  24.                 @Html.TextBoxFor(a => a.MobileName)  
  25.                 @Html.ValidationMessageFor(a => a.MobileName)  
  26.             </td>  
  27.         </tr>  
  28.         <tr>  
  29.             <td>  
  30.                 @Html.LabelFor(a => a.MobileIMEno)  
  31.             </td>  
  32.         </tr>  
  33.         <tr>  
  34.             <td>  
  35.                 @Html.TextBoxFor(a => a.MobileIMEno)  
  36.                 @Html.ValidationMessageFor(a => a.MobileIMEno)  
  37.             </td>  
  38.         </tr>  
  39.         <tr>  
  40.             <td>  
  41.                 @Html.LabelFor(a => a.mobileManufacured)  
  42.             </td>  
  43.         </tr>  
  44.         <tr>  
  45.             <td>  
  46.                 @Html.TextBoxFor(a => a.mobileManufacured)  
  47.                 @Html.ValidationMessageFor(a => a.mobileManufacured)  
  48.             </td>  
  49.         </tr>  
  50.         <tr>  
  51.             <td>  
  52.                 @Html.LabelFor(a => a.mobileprice)  
  53.             </td>  
  54.         </tr>  
  55.         <tr>  
  56.             <td>  
  57.                 @Html.TextBoxFor(a => a.mobileprice)  
  58.                 @Html.ValidationMessageFor(a => a.mobileprice)  
  59.             </td>  
  60.         </tr>  
  61.         <tr>  
  62.             <td colspan="2">  
  63.                 <input id="Submit1" type="submit" value="submit" />  
  64.             </td>  
  65.         </tr>  
  66.     </table>  
  67. }  
Now just run your application and check output.
 

After Adding Insert code on [Httppost]:
  1. [HttpPost]  
  2. public ActionResult InsertMobile(Mobiledata MB) // Calling on http post (on Submit)  
  3. {  
  4.     if (ModelState.IsValid) //checking model is valid or not  
  5.     {  
  6.         DataAccessLayer.DBdata objDB = new DataAccessLayer.DBdata(); //calling class DBdata  
  7.         string result = objDB.InsertData(MB); // passing Value to DBClass from model  
  8.         ViewData["result"] = result;  
  9.         ModelState.Clear(); //clearing model  
  10.         return View();  
  11.     }  
  12.     else  
  13.     {  
  14.         ModelState.AddModelError("""Error in saving data");  
  15.         return View();  
  16.     }  
  17. }  
On cs.html

Added this to display message after saving data.

  1. @{  
  2.     if (ViewData["result"] != "" && ViewData["result"] != null)  
  3.     {  
  4.         ViewData["result"] = null;  
  5.     <script type="text/javascript" language="javascript">  
  6.         alert("Data saved Successfully");  
  7.     </script>  
  8.     }  
  9. }  
Run the application and insert records into it.
 
 

Now we have completed the Insert part.

Next we will create a basic grid view for displaying records.

For that we will add a new View but using the same Controller.

Let's begin with adding a View. A strongly typed View.
  1. public ActionResult ShowAllMobileDetails(Mobiledata MB)  
  2. {  
  3.     return View();  
  4. }  
After creating Action Result just right-click on ActionResult and select Add View.

And also check:
  1. Create a strongly-typed view option
  2. Use a layout or master page

Select the same Model as we used when creating InsertMobile.

Just click on the Add button.

A new View has been created.


After this in the Model I am adding new Properties as in the following:

public DataSet StoreAllData { get; set; }

For storing values in a dataset and displaying values from a dataset on the View.

Because in MVC you can access a complete Model in a View.

In ActionResult I will access DBdata and get the dataset and pass it to a model dataset name.

(StoreAlldata)
  1. public ActionResult ShowAllMobileDetails(Mobiledata MB)  
  2. {  
  3.      DataAccessLayer.DBdata objDB = new DataAccessLayer.DBdata(); //calling class DBdata  
  4.      MB.StoreAllData = objDB.SelectAllData();  
  5.      return View(MB);  
  6. }   
After this on the view I will display data from the dataset using a for loop.

And also adding the 2 linkbuttons Edit and Delete.

  1. @Html.ActionLink("EDIT""EDITMOBILEDATA"new { id = Model.StoreAllData.Tables[0].Rows[i]["MobileID"].ToString() })   
  2. @Html.ActionLink("Delete""DELETEMOBILEDATA"new { id = Model.StoreAllData.Tables[0].Rows[i]["MobileID"].ToString() })   
Example 

EDIT name of Button.

EDITMOBILEDATA is the name of the page; on a click it will redirect with id.

  1. @model MymobilewalaMvc.Models.Mobiledata  
  2. @{  
  3.     ViewBag.Title = "ShowAllMobileDetails";  
  4. }  
  5. <h2>  
  6.     ShowAllMobileDetails</h2>   
  7. <table>  
  8.     <tr>  
  9.         <td>  
  10.             @Html.ActionLink("Add New Mobiles""InsertMobile")  
  11.         </td>  
  12.     </tr>  
  13. </table>   
  14. @{  
  15.     for (int i = 0; i < Model.StoreAllData.Tables[0].Rows.Count; i++)  
  16.     {  
  17.         var MobileID = Model.StoreAllData.Tables[0].Rows[i]["MobileID"].ToString();  
  18.         var MobileName = Model.StoreAllData.Tables[0].Rows[i]["MobileName"].ToString();  
  19.         var MobileIMEno = Model.StoreAllData.Tables[0].Rows[i]["MobileIMEno"].ToString();  
  20.         var Mobileprice = Model.StoreAllData.Tables[0].Rows[i]["mobileprice"].ToString();  
  21.         var MobileManufacured = Model.StoreAllData.Tables[0].Rows[i]["mobileManufacured"].ToString();    
  22.     <table width="100%">  
  23.         <tr>  
  24.             <td>  
  25.                 MobileID  
  26.             </td>  
  27.             <td>  
  28.                 MobileName  
  29.             </td>  
  30.             <td>  
  31.                 Mobile IMEI No  
  32.             </td>  
  33.             <td>  
  34.                 Mobileprice  
  35.             </td>  
  36.             <td>  
  37.                 Mobile Manufactured  
  38.             </td>  
  39.             <td>  
  40.                 EDIT  
  41.             </td>  
  42.             <td>  
  43.                 DELETE  
  44.             </td>  
  45.         </tr>  
  46.         <tr>  
  47.             <td>  
  48.                 @MobileID  
  49.             </td>  
  50.             <td>  
  51.                 @MobileName  
  52.             </td>  
  53.             <td>  
  54.                 @MobileIMEno  
  55.             </td>  
  56.             <td>  
  57.                 @Mobileprice  
  58.             </td>  
  59.             <td>  
  60.                 @MobileManufacured  
  61.             </td>  
  62.             <td>  
  63.                 @Html.ActionLink("EDIT""EDITMOBILEDATA"new { id = Model.StoreAllData.Tables[0].Rows[i]["MobileID"].ToString() })  
  64.             </td>  
  65.             <td>  
  66.                 @Html.ActionLink("Delete""DELETEMOBILEDATA"new { id = Model.StoreAllData.Tables[0].Rows[i]["MobileID"].ToString() })  
  67.             </td>  
  68.         </tr>  
  69.         <tr>  
  70.             <td>  
  71.                 @Html.ActionLink("Add New Mobiles""InsertMobile")  
  72.             </td>  
  73.         </tr>  
  74.     </table>  
  75.     }   
  76. }  
View of ShowAllMobileDetails:
 

Let's now add two new Views to the same controller.

1. EDITMOBILEDATA

In this ActionResult I have provided a string id to the method to receive an ID when I click on the Edit button.

After getting the ID, get data from the database depending on that id and display record.
  1. public ActionResult EDITMOBILEDATA(string id)  
  2. {  
  3.     DataAccessLayer.DBdata objDB = new DataAccessLayer.DBdata();   
  4.     //calling class DBdata  
  5.     DataSet ds = objDB.SelectAllDatabyID(id);  
  6.     Mobiledata MB = new Mobiledata();  
  7.     MB.MobileID = Convert.ToInt32(ds.Tables[0].Rows[0]["MobileID"].ToString());  
  8.     MB.MobileName = ds.Tables[0].Rows[0]["MobileName"].ToString();  
  9.     MB.MobileIMEno = ds.Tables[0].Rows[0]["MobileIMEno"].ToString();  
  10.     MB.mobileprice = ds.Tables[0].Rows[0]["mobileprice"].ToString();  
  11.     MB.mobileManufacured = ds.Tables[0].Rows[0]["mobileManufacured"].ToString();  
  12.     return View(MB);  
  13. }   
Just right-click on ActionResult and add a View of a strong type.
 

After adding the view I will design the View to edit and update data.
  1. @model MymobilewalaMvc.Models.Mobiledata  
  2. @{  
  3.     ViewBag.Title = "EDITMOBILEDATA";  
  4. }  
  5. <h2>  
  6.     EDITMOBILEDATA</h2>   
  7. <table>  
  8.     <tr>  
  9.         <td>  
  10.             @Html.ActionLink("Show All Mobile List""ShowAllMobileDetails")  
  11.         </td>  
  12.     </tr>  
  13. </table>  
  14. <br />    
  15. @using (Html.BeginForm())  
  16. {   
  17.     <table width="100%">  
  18.         <tr>  
  19.             <td colspan="2">  
  20.                 @Html.HiddenFor(a => a.MobileID)  
  21.             </td>  
  22.         </tr>  
  23.         <tr>  
  24.             <td>  
  25.                 @Html.LabelFor(a => a.MobileName)  
  26.             </td>  
  27.         </tr>  
  28.         <tr>  
  29.             <td>  
  30.                 @Html.TextBoxFor(a => a.MobileName)  
  31.                 @Html.ValidationMessageFor(a => a.MobileName)  
  32.             </td>  
  33.         </tr>  
  34.         <tr>  
  35.             <td>  
  36.                 @Html.LabelFor(a => a.MobileIMEno)  
  37.             </td>  
  38.         </tr>  
  39.         <tr>  
  40.             <td>  
  41.                 @Html.TextBoxFor(a => a.MobileIMEno)  
  42.                 @Html.ValidationMessageFor(a => a.MobileIMEno)  
  43.             </td>  
  44.         </tr>  
  45.         <tr>  
  46.             <td>  
  47.                 @Html.LabelFor(a => a.mobileManufacured)  
  48.             </td>  
  49.         </tr>  
  50.         <tr>  
  51.             <td>  
  52.                 @Html.TextBoxFor(a => a.mobileManufacured)  
  53.                 @Html.ValidationMessageFor(a => a.mobileManufacured)  
  54.             </td>  
  55.         </tr>  
  56.         <tr>  
  57.             <td>  
  58.                 @Html.LabelFor(a => a.mobileprice)  
  59.             </td>  
  60.         </tr>  
  61.         <tr>  
  62.             <td>  
  63.                 @Html.TextBoxFor(a => a.mobileprice)  
  64.                 @Html.ValidationMessageFor(a => a.mobileprice)  
  65.             </td>  
  66.         </tr>  
  67.         <tr>  
  68.             <td colspan="2">  
  69.                 <input id="Submit1" type="submit" value="Update" />  
  70.             </td>  
  71.         </tr>  
  72.     </table>     
  73. }  
  74. @{  
  75.     if (ViewData["resultUpdate"] != "" && ViewData["resultUpdate"] != null)  
  76.     {  
  77.         ViewData["resultUpdate"] = null;  
  78.     <script type="text/javascript" language="javascript">  
  79.         alert("Data Updated Successfully");  
  80.     </script>  
  81.     }  
  82. }  
 

After clicking on the Edit Button from ShowAllmobileDetails.


Creating the same ActionResult of EDITMOBILEDATA with a model as a parameter for postdata.
  1. [HttpPost]  
  2. public ActionResult EDITMOBILEDATA(Mobiledata MD)  
  3. {  
  4.      DataAccessLayer.DBdata objDB = new DataAccessLayer.DBdata(); //calling class DBdata  
  5.      string result = objDB.UpdateData(MD); // passing Value to DBClass from model  
  6.      ViewData["resultUpdate"] = result; // for dislaying message after updating data.  
  7.      return RedirectToAction("ShowAllMobileDetails""Mobilestore");   
  8. }  
This will post data when the user will click the Update Button.
 

Adding the last View to delete records.

2. DELETEMOBILEDATA

In this ActionResult I have given a string id to the method to receive an ID when I click on the Delete button.

1. After getting an ID get data from the database and depending on that id display complete records and then it is possible to delete records.
  1. public ActionResult DELETEMOBILEDATA(string id)  
  2. {  
  3.     DataAccessLayer.DBdata objDB = new DataAccessLayer.DBdata();   
  4.     //calling class DBdata  
  5.     DataSet ds = objDB.SelectAllDatabyID(id);  
  6.     Mobiledata MB = new Mobiledata();  
  7.     MB.MobileID = Convert.ToInt32(ds.Tables[0].Rows[0]["MobileID"].ToString());  
  8.     MB.MobileName = ds.Tables[0].Rows[0]["MobileName"].ToString();  
  9.     MB.MobileIMEno = ds.Tables[0].Rows[0]["MobileIMEno"].ToString();  
  10.     MB.mobileprice = ds.Tables[0].Rows[0]["mobileprice"].ToString();  
  11.     MB.mobileManufacured = ds.Tables[0].Rows[0]["mobileManufacured"].ToString();  
  12.     return View(MB);  
  13. }  
Right-click on Actionresult then select Add View.
 

After adding a Design View to show records when deleting.
  1. @model MymobilewalaMvc.Models.Mobiledata  
  2. @{  
  3.     ViewBag.Title = "DELETEMOBILEDATA";  
  4. }  
  5. <h2>  
  6.     DELETEMOBILEDATA</h2>  
  7. <table>  
  8.     <tr>  
  9.         <td>  
  10.             @Html.ActionLink("Add New Mobiles""InsertMobile")  
  11.         </td>  
  12.         <td>  
  13.             @Html.ActionLink("Show All Mobile List""ShowAllMobileDetails")  
  14.         </td>  
  15.     </tr>  
  16. </table>  
  17. <br />  
  18. @using (Html.BeginForm())  
  19. {   
  20.     <table width="100%">  
  21.         <tr>  
  22.             <td colspan="2">  
  23.                 @Html.HiddenFor(a => a.MobileID)  
  24.             </td>  
  25.         </tr>  
  26.         <tr>  
  27.             <td>  
  28.                 MobileName :-  
  29.                 @Html.DisplayFor(a => a.MobileName)  
  30.             </td>  
  31.         </tr>  
  32.         <tr>  
  33.             <td>  
  34.                 MobileIMEI Number:-  
  35.                 @Html.DisplayFor(a => a.MobileIMEno)  
  36.             </td>  
  37.         </tr>  
  38.         <tr>  
  39.             <td>  
  40.                 Mobile Manufacured :-  
  41.                 @Html.DisplayFor(a => a.mobileManufacured)  
  42.             </td>  
  43.         </tr>  
  44.         <tr>  
  45.             <td>  
  46.                 Mobileprice :-  
  47.                 @Html.DisplayFor(a => a.mobileprice)  
  48.             </td>  
  49.         </tr>  
  50.         <tr>  
  51.             <td colspan="2">  
  52.                 <input id="Submit1" onclick="return confirm('Are you sure you want delete');" type="submit"  
  53.                     value="Delete" />  
  54.             </td>  
  55.         </tr>  
  56.     </table>  
  57. }  
Creating the same ActionResult of DELETEMOBILEDATA with a model as a parameter for postdata.
  1. [HttpPost]  
  2. public ActionResult DELETEMOBILEDATA(Mobiledata MD)  
  3. {  
  4.     DataAccessLayer.DBdata objDB = new DataAccessLayer.DBdata();   
  5.     //calling class DBdata  
  6.     string result = objDB.DeleteData(MD);  
  7.     return RedirectToAction("ShowAllMobileDetails""Mobilestore");  
  8. }  
This will post data when the user clicks the Delete Button.
 

Finally we are completed with insert, update, and delete in MVC.
 
 
 
 


Similar Articles