So based on preceding scenario let's start building application step by step so beginners can also understand .
Step 1: Create an MVC Application.
Now let us start with a step by step approach from the creation of a simple MVC application as in the following:
- "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
- "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
- As shown in the preceding screenshot, click on Empty template and check MVC option, then click OK. This will create an empty MVC web application.
Step 2 : Add The Reference of Dapper ORM into Project.
Now next step is to add the reference of Dapper ORM into our created MVC Project. Here are the steps:
- Right click on Solution ,find Manage NuGet Package manager and click on it.
- After as shown into the image and type in search box "dapper".
- Select Dapper as shown into the image .
- Choose version of dapper library and click on install button.
After installing the Dapper library, it will be added into the References of our solution explorer of MVC application such as:
If wants to learn how to install correct Dapper library , watch my video tutorial using following link,
I hope you have followed the same steps and installed dapper library.
Step 3: Create Model Class.
Now let's create the model class named ComplaintModel.cs by right clicking on model folder as in the following screenshot:
Note:
It is not mandatory that Model class should be in Model folder, it is just for better readability you can create this class anywhere in the solution explorer. This can be done by creating different folder name or without folder name or in a separate class library.
ComplaintModel.cs class code snippet:
- public class ComplaintModel
- { [Display(Name = "Complaint Type")]
- [Required]
- public string ComplaintType { get; set; }
- [Display(Name = "Complaint Description")]
- [Required]
- public string ComplaintDesc { get; set; }
- }
Step 4 : Create Controller.
Now let us add the MVC 5 controller as in the following screenshot:
After clicking on
Add button it will show the window. specify the
Controller name as Complaint with suffix
Controller:
Note: The controller name must be having suffix as 'Controller' after specifying the name of controller.
Step 5 : Create Table and Stored procedure.
Now before creating the views let us create the table name ComplaintDetails in database according to store the complaint details:
I hope you have created the same table structure as shown above. Now create the stored procedures to get the return value as in the following code snippet:
- Create PROCEDURE AddComplaint
- (
- @ComplaintType varchar(100),
- @ComplaintDesc varchar(150),
- @ComplaintId varchar(20)=null out
- )
- AS
- BEGIN
- SET NOCOUNT ON;
-
- Declare @ComplaintRef varchar(30)
-
- select @ComplaintRef=isnull(max(Id),0)+1 from ComplaintDetails
-
- Set @ComplaintId=Upper(LEFT(@ComplaintType,4))+convert(Varchar,@ComplaintRef)
-
- INSERT INTO [dbo].[ComplaintDetails]
- (
- [ComplaintId]
- ,[ComplaintType]
- ,[ComplaintDesc]
- )
- VALUES
- (
- @ComplaintId,
- @ComplaintType,
- @ComplaintDesc
- )
- END
Run the above script in sql it will generates the stored procedure to get the return value .
Step 6: Create Repository class.
Now create Repository folder and Add ComplaintRepo.cs class for database related operations, Now create method in ComplaintRepo.cs to get the output parameter value from stored procedure as in the following code snippet:
- public class ComplaintRepo
- {
- SqlConnection con;
-
- private void connection()
- {
- string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();
- con = new SqlConnection(constr);
- }
-
- public string AddComplaint(ComplaintModel Obj)
- {
- DynamicParameters ObjParm = new DynamicParameters();
- ObjParm.Add("@ComplaintType", Obj.ComplaintType);
- ObjParm.Add("@ComplaintDesc", Obj.ComplaintDesc);
- ObjParm.Add("@ComplaintId", dbType:DbType.String,direction:ParameterDirection.Output,size:5215585);
- connection();
- con.Open();
- con.Execute("AddComplaint",ObjParm,commandType:CommandType.StoredProcedure);
-
- var ComplaintId = ObjParm.Get<string>("@ComplaintId");
- con.Close();
- return ComplaintId;
-
- }
- }
Note
- In the above code we are manually opening and closing connection, however you can directly pass the connection string to the dapper without opening it. Dapper will automatically handle it.
Step 7: Create Method into the ComplaintController.cs file.
Now open the ComplaintController.cs and create the following action methods:
- public class ComplaintController : Controller
- {
-
- public ActionResult AddComplaint()
- {
- return View();
- }
- [HttpPost]
- public ActionResult AddComplaint(ComplaintModel ObjComp)
- {
- try
- {
- ComplaintRepo Obj = new ComplaintRepo();
-
-
- ViewBag.ComplaintId = "Complaint raised successfully, Your complaintId is " + Obj.AddComplaint(ObjComp);
- }
- catch (Exception)
- {
-
- ViewBag.ComplaintId="Error while raising complaint, Please check details";
- }
- return View();
- }
- }
Step 8 : Creating strongly typed view named
AddComplaint using
ComplaintModel class .
Right click on View folder of created application and choose add view , select ComplaintModel class and create scaffolding template to create view to raise the user complaints as
Click on Add button then it will create the view named AddComplaint, Now open the AddComplaint.cshtml view , Then following default code you will see which is generated by MVC scaffolding template as,
AddComplaint.cshtml
- @model GetReturnValueUsingDapperInMVC.Models.ComplaintModel
-
- @{
- ViewBag.Title = "www.compilemode.com";
- }
-
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
-
- <div class="form-horizontal">
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.ComplaintType, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.ComplaintType, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.ComplaintType, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.ComplaintDesc, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.ComplaintDesc, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.ComplaintDesc, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Add Complaint" class="btn btn-primary" />
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10 text-success">
- @ViewBag.ComplaintId
- </div>
- </div>
- </div>
- }
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/jquery.validate.min.js"></script>
- <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
After adding model, view , controller and Repository folder our final solution explorer will be look like as follows,
Now we have done all coding to upload files .
Step 9 : Now run the application.
After running the application initial screen will be look like as follows,
Now click on Add Complaint button without entering the details then the following error message shows which we have defined in model class as
Now enter the proper details as,
Now click on Add complaint button, It will shows the following message with ComplaintId which is returned by stored procedure after successfully adding the complaint as,
I hope from all thepreceding example we have learned how to get return value from stored procedure using Dapper ORM in ASP.NET MVC with real time scenario based sample MVC application.
Note:
- Download the Zip file of the sample application for a better understanding.
- Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
- Configure the database connection in the web.config file depending on your database server location.
- You can use DropDownList for complaint types which might be come from master table.
Summary
I hope this article is useful for all readers. If you have any suggestions please contact me.
Read more articles on ASP.NET: