Key Value Pair Auto complete TextBox In ASP.NET MVC

Some application need to use auto complete text box with key and value pair which populates the records with the combination of key and its value when user types into the textbox , Its good approach to avoid dropdownlist which is not fit if the records are too much and selecting them is very difficult task.

Key value pair means suppose we need to populate records with employee Id along with his or her name or it may be anything as per your requirement.  So lets demonstrate this requirement with the help of sample ASP.NET MVC application .

Step 1 :
Create an MVC application.
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
  3. Choose MVC empty application option and click on OK
Step 2: Add model class.

Right click on Model folder in the created MVC application and add class named Employee and write the following line of code,

City.cs
public class Employee
  {  
      public int Id { get; set; }  
      public string Name { get; set; }  
  
  }  
Step 3: Add user and admin controller

Right click on Controller folder in the created MVC application and add the controller class as:


Now after selecting controller template, click on add button then then another  following window appears,Specify the controller name and click on add button,
Now open the HomeController.cs file and write the following code into the Home controller class to bind and create the generic list from model class as in the following,

HomeController.cs
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoCompleteInMVCJson.Models;

namespace AutoCompleteInMVCJson.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Index(string Prefix)
        {
            //Note : you can bind same list from database  
            List<Employee> ObjList = new List<Employee>()
            {

                new Employee {Id=100,Name="Vithal Wadje" },
                new Employee {Id=200,Name="Sudir Wadje" },
                new Employee {Id=300,Name="Sachin W" },
                new Employee {Id=400,Name="Vikram N" }


        };
            //Searching records from list using LINQ query  
            var EmpDet = (from N in ObjList
                          where N.Id.ToString().StartsWith(Prefix)|| N.Name.ToLower().StartsWith(Prefix.ToLower())
                          select new { N.Name, N.Id });
            return Json(EmpDet, JsonRequestBehavior.AllowGet);
        }
    }
}



In the above code, instead of going to database for records we are creating the generic list from model class and we will fetch records from above generic list.

Step 4:
Reference jQuery UI css and js library reference as there are many ways to add the reference of jQuery library into the our project. The following are some methods:
  • Using NuGet package manager , you can install library and reference into the project
  • Use CDN library provided by Microsoft, jQuery, Google or any other which requires active internet connection.
  • Download jQuery files from jQuery official website and reference into the project.
In this example we will use jQuery CDN library.

Step 5: Create jQuery Ajax function to call controller JSON action method and invoke autocomplete function,

<script type="text/javascript">
    $(document).ready(function () {
        $("#Name").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Id+"-"+item.Name, value: item.Id };
                        }))

                    }
                })
            }
            
        });
    })
</script>


To work above function don't forget to add the reference of the following jQuery CDN library as,

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  
<script src="//code.jquery.com/jquery-1.10.2.js"></script>  
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
Step 6:
Add view named index and put above json function into the view. After adding code necessary files and logic the Index.cshtml will look like the following,
Index.cshtml


@model AutoCompleteInMVCJson.Models.Employee
@{
    ViewBag.Title = "www.compilemode.com";
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#Name").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Id+"-"+item.Name, value: item.Id };
                        }))

                    }
                })
            }
            
        });
    })
</script>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <hr />

        <div class="form-group">

            <div class="col-md-12">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

            </div>
        </div>

    </div>
}

Searching by Key or ID
 
Now run the application and type any key or Id then it will auto populate the records which exactly start with first key as in the following screenshot,



Searching by Name or Value

Now run the application and type any name then it will auto populate the records which exactly start with first word as in the following screenshot,


   
Selected Record 

Now select any key value pair , it will set the key in the textbox instead of value you may change vise versa .



From all the above examples, I hope you learned how to create the auto complete key value pair textbox using jQuery UI in ASP.NET MVC.
Note:
  • Perform changes in code as per your requirement  its just example .
  • Follow proper standards which might be not meet with this given code.
  • You need to use the jQuery library.
    Summary
    I hope this article is useful for all readers, If you have a suggestion then please contact me.
    Don't Forget To 

    How To Publish ASP.NET Web API REST Service In File System

    When you want any application available publicly, you need to host it on the server and before hosting, it requires certain processes in terms of making an Application code suitable to the host. Thus, in this article, we will learn how to publish ASP.NET Web API Applications, using File system method. Therefore, let's start step by step, so beginners can also understand .
    What is Publishing ?
    Publishing is the process to make an Application code suitable to host on the Server by merging multiple class codes into DLLs and by keeping only the required UI code .
    The Web Application goes through the steps, mentioned below before hosting to the Server.
    Develop an Application -- Publish an Application - Host an Application on IIS.
    Now, just demonstrate the preceding concept step by step; i.e, how to publish ASP.NET Web API Applications practically. 
    Step 1 
    Create ASP.NET Web API application
    If you want to publish any Application, first we need to create the Application. If you don't know how to create ASP.NET Web API Application, please refer to my previous article, mentioned below.
    Also you can watch video which explains how to create ASP.NET Web API REST service step by step



    I hope, you have created ASP.NET Application by reading the preceding article .
    Step 2
    Publish an Application
    Right click on the created ASP.NET Web API project solution, as shown below.


    Now, click the previously shown Publish option. It will open the Windows, mentioned below.
    Step 3
    Select Publish Target
    Now, select the option, where you want to save the published file. There are lots of options given by Visual Studio to save the published files, as shown below.


    In the preceding image, we have seen that there are many options listed to publish the application, let's learn about them in brief.
    • Microsoft Azure App Service
      This is one of the services provided by Microsoft Azure to publish the different types of the Application such as Web, mobile, REST and other into Azure (Cloud). You need a Microsoft Azure subscription to use this option.
    • Import 
      This option is used to publish the Application, which is based on the predefined configuration files given by your hosting provider , which will directly publish the files in your hosting provider environment.
    • Custom 
      This option is used to publish the Application into your own machine location or FTP Server, as per your most convenient way.
    • Microsoft Azure API apps This option is used to publish REST API's Services in Cloud.
    • Microsoft Azure virtual machineThis option is used to publish the Application in Microsoft Azure virtual machine (Cloud), which requires an Azure subscription . 
    There are many other options to publish the Application, using which we can publish .NET Application.
    Step 4
    Create Custom profile
    Now, in this article, we are going to publish an Application in our local machine file system, so we need to choose custom target option. First, we need to create the profile to publish the Application, so it can be a consistent setting to publish the same Application in the future. Choose custom option from preceding explained target option, as shown below.


    Now, give the profile name as per your requirement and click OK. It will create the custom profile, as per your given name.
    Step 5
    Choose Publish Method
    Now, configure the created profile, which decides where and how to publish the files. Select the Publish method from the number of methods, which are shown below.


    Now, choose the file system method from preceding methods and click Next button.
    Step 6
    Choose File System location
    Now, choose the target location of your local system in which you want to store the published files, as shown below.


    In the preceding screenshot, we have selected the target location E drive to store the published files. It may be different in your case, as per you machine and click Next button .
    Step 7
    Choose Publish code type
    Now, choose what type of code you want in production environment by choosing release or debug option, as shown below.


    Now, let's learn in brief about debug and release option.
    • DebugChoose this option when you want to debug your Application after the hosting.
    • ReleaseChoose this option when you do not want to debug the Application after hosting and make the Application faster . 
    Step 8
    Preview the configuration
    After the configuration, publish configuration tool will look like, as shown below.


    Now, click Publish option and watch the output Window, as shown below.


    Now, as shown in the preceding screenshot's highlighted section, our Application code is published in our specified file system location. Now, navigate to the target folder and see the published files, as shown below.


    We have seen our published code, which is used to host in IIS. I hope from all the preceding examples, we learned how to publish ASP.NET Web API Service in File system .
    Note
    • Choose the publish target location, as per your system.
    • Select proper publish method, as per your requirement.
    Summary

    I hope, this article is useful for all the readers. If you have any suggestions, please contact me.

    Don't Forget To 

    Check UserName Exists or Not instantly In ASP.NET MVC

    Many times, we need to check instantly whether a record already exists in the database or not. For example, at the time of signup, we need to check if the user is already registered with current Email id, or the username is already taken. So, to achieve these functionalities, there are many methods, but in ASP.NET MVC, there is a very easy way to achieve these types of functionalities, i.e. with the help of remote attributes. Let's learn step by step how to check user instantly, using remote attribute in ASP.NET MVC.

    What is Remote Validation in ASP.NET MVC ?

    Remote is the attribute for validation in Data Annotation, which is used in model class to validate records instantly. Let's demonstrate the aforementioned concept by creating sample ASP.NET MVC application.
    Step 1 - Create an MVC Application

    Now, let us start with a step-by-step approach from the creation of a simple MVC application.
    1. Go to "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
    2. Click "File", followed by "New" and click "Project". 
    3. Select "ASP.NET Web Application Template", provide the Project a name of your choice and click OK. 
    After clicking, the following window will appear.

    Step 2 - Create Model Class

    Now, let us create the model class, named RegisterModel.cs, by right clicking on Models folder, as
    shown in the screenshot.


    After creating the class, write the following properties in RegisterModel.cs class.

    RegisterModel.cs

    using System.ComponentModel.DataAnnotations;  
    using System.Web.Mvc;  
      
    namespace RemoteValiDationInMVC.Models  
    {  
        public class RegisterModel  
        {  
              
            [Required]  
            [DataType(DataType.EmailAddress)]  
            [Display(Name ="Enter EmailId")]  
            //Using Remote validation attribute   
            [Remote("IsAlreadySigned", "Register",HttpMethod ="POST", ErrorMessage = "EmailId already exists in database.")]  
            public string UserEmailId { get; set; }  
            [Required]  
            public string Designation { get; set; }  
                     
            [Required]  
            [DataType(DataType.Password)]  
            [Display(Name =("Choose Password"))]  
            public string PassWord { get; set; }  
      
        }  
    }  

    In the preceding code, we have used Remote attribute for UserEmaiId model class method with some properties which are explained below.



    In the above image, we have defined a few properties of Remote attribute to work on remote validation properly, let's know them in brief.
    • IsAlreadySigned
      This is the JsonResult method which checks the details from database and returns true or false.
    • Register
      This is MVC Controller name and inside that, IsAlreadySigned JsonResult method is defined to check the details from database.
    • HttpMethod
      This is HttpMethod type which is called on Remote attribute e.g. Get , Put , Post. This is optional to define.
    • ErrorMessage
      This is used to show the message at client side. 
    There are many optional properties of Remote attribute which are used as per the validation requirements.
    Step 3 - Add Controller Class
    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 Register with suffix Controller. Now, modify the default code in RegisterController.cs class file and create JsonResult method. After modifying, the code will look like as follows.

    RegisterController.cs

    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web.Mvc;  
    using RemoteValiDationInMVC.Models;  
      
    namespace RemoteValiDationInMVC.Controllers  
    {  
        public class RegisterController : Controller  
        {  
            // GET: Register  
            [HttpGet]  
            public ActionResult SignUp()  
            {  
                return View();  
            }  
            [HttpPost]  
            public ActionResult SignUp(RegisterModel ObjModel )  
            {  
                if (ModelState.IsValid)  
                {  
      
                    return View();  
      
                }  
                else  
                {  
      
                    return View();  
      
                }  
      
            }  
            [HttpPost]  
            public JsonResult IsAlreadySigned(string UserEmailId)  
            {  
                  
                return Json(IsUserAvailable(UserEmailId));  
      
            }  
            public bool IsUserAvailable(string EmailId)  
            {  
                // Assume these details coming from database  
            List<RegisterModel> RegisterUsers = new List<RegisterModel>()  
            {  
      
                new RegisterModel {UserEmailId="vithal.wadje@abc.com" ,PassWord="compilemode",Designation="SE"},  
                new RegisterModel {UserEmailId="Sudhir@abc.com" ,PassWord="abc123",Designation="Software Dev"}  
      
            };  
                var RegEmailId = (from u in RegisterUsers  
                                  where u.UserEmailId.ToUpper() == EmailId.ToUpper()  
                                  select new { EmailId }).FirstOrDefault();  
      
                bool status;  
                if (RegEmailId!=null)  
                {  
                    //Already registered  
                    status = false;  
                }  
                else  
                {  
                    //Available to use  
                   status = true;  
                }  
                    
                return status;  
          }            
        }  
      
    }  

    Note

    In the preceding code, IsAlreadySigned returns the JSON data at client side and it takes the UserEmailId as input parameter, the name of which, must match with the get set property defined under the remote attribute.

    Step 4 - Create View

    Now, let's create StronglyTyped View named SignUp from RegisterModel class.


    Click on Add button. It will create the View named SignUp. Now, open the SignUp.cshtml View. You will see some default code which is generated by MVC scaffolding template. Let's now, modify the default code to make as per our requirement.

    SignUp.cshtml

    @model RemoteValiDationInMVC.Models.RegisterModel  
      
    @{  
        ViewBag.Title = "SignUp";  
    }  
    @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.UserEmailId, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.UserEmailId, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.UserEmailId, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.Designation, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.Designation, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.Designation, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.PassWord, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.PassWord, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.PassWord, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                <div class="col-md-offset-2 col-md-10">  
                    <input type="submit" value="SignUp" class="btn btn-primary" />  
                </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 the Model, add View and Controller into our project, the Solution Explorer will look like the following.


    Step - 5 

    Now, run the application and type emaild id which is already in the  list that we defined in the RegisterController class.

    Now, without posting the form, it's showing instantly that the given email id already exists in the database, This approach will save a lot of time for the user in unnecessary validation.
    Note
    • Since this is a demo, it might not be using proper standards. So, improve it as per your own skills.
    Summary
    I hope this article is useful for all readers. If you have any suggestions, please contact me.
    Don't Forget To 

    Return Value From Dapper with Stored Procedure

    Sometimes in an  we need to give user acknowledgment of their raised request or transaction reference number instantly from database which is generated against that user request. So for this purpose we need to take return value from stored procedure which is either string or integer or anything as per application requirement. Now in this article we will learn how to get return value from stored procedure using Dapper ORM in ASP.NET MVC with one scenario-based sample MVC application.
    Scenario
     Let's consider ABC housing society provides different services to their flat owners.  Since ABC housing society is very big it's difficult to manage complaints manually of their flat customers, so they decided to build the sample application which covers the following scenario .
    • User can raise the complaint type and short description using Text boxes .
    • The unique ComplaintId need to be generated instantly after raising the complaint to track status.
    • The ComplaintId should be the combination of first four characters of complaint type text and Database auto generated number.
    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:
    1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    2. "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:
    1. 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:
    1. Right click on Solution ,find Manage NuGet Package manager and click on it.
    2. After as shown into the image and type in search box "dapper".
    3. Select Dapper as shown into the image .
    4. 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)  
    --Getting unquie Id  
    select @ComplaintRef=isnull(max(Id),0)+1 from ComplaintDetails  
    --Generating the unique reference number and seeting to output parameter  
    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;  
          //To Handle connection related activities  
          private void connection()  
          {  
              string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();  
              con = new SqlConnection(constr);  
          }  
          //To Add Complaint details  
          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);  
              //Getting the out parameter value of stored procedure  
              var ComplaintId = ObjParm.Get<string>("@ComplaintId");  
              con.Close();  
              return ComplaintId;  
      
          }  
      }  
    Note
    1. 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  
       {  
           // GET: complaint  
           public ActionResult AddComplaint()  
           {  
               return View();  
           }  
           [HttpPost]  
           public ActionResult AddComplaint(ComplaintModel ObjComp)  
           {  
               try  
               {  
                   ComplaintRepo Obj = new ComplaintRepo();  
                   //Getting complaintId and assigning   
                   //to ViewBag with custom message to show user  
                   ViewBag.ComplaintId = "Complaint raised successfully, Your complaintId is " + Obj.AddComplaint(ObjComp);  
               }  
               catch (Exception)  
               {  
                   //Assigning custom message to ViewBag to show users, If any error occures.  
                   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,

    I hope from all the preceding 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:

    • 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 MVC:

    My Upcoming Speaking : Building Distributed Architecture using ASP.NET Web API with Azure SQL Database

    Speaking at C# Corner Pune Chapter event on Building Distributed Architecture using ASP.NET Web API with Azure SQL Database , If you wants to learn how to build and decide architecture for application  then join my interactive session on Building Distributed Architecture using ASP.NET Web API with Azure SQL Database.

    Agenda

     Date : 19-11-2016


    Building Distributed Architecture using ASP.NET Web API with Azure SQL Database
    • User Story
    • What is a Distributed Architecture?
    • Tier Vs Layer Architecture
    • WCF REST Vs Web API REST?
    • Designing & understanding Distributed architecture diagram
    • Building REST Service Layer
    • Building Business Logic Layer
    • Building Entity Layer
    • Building Data Access Layer with Dapper ORM
    • Creating Azure SQL database
    • Connecting Data Access Layer with Azure SQL database
    • Building Client Layer with ASP.NET MVC
    • Hosting layers on different machines
    • Consuming Web API REST Services in ASP.NET MVC using HttpClient
    • Consuming Web API REST Services in Windows Phone and Windows Application
    • Q & A


          Where:

          Fujitsu Consulting India
          A-15, IT Tower, M I D C Technology Park, 
          Talwade , Pimpri-Chinchwad - 412114
          Pune Maharashtra INDIA


          Price: Free of cost

          Requirement: Optional to bring your laptop and internet card.

          Date : 19-11-2016
          Time :04:00 PM - 05:30 PM

                                        Register Now

          Don't forget to connect with me

          www.CodeNirvana.in

          Protected by Copyscape Online Copyright Protection
          Copyright © Compile Mode