Display Country List Without Database in ASP.NET MVC

Many time we need list of countries to use in an application to serve the particular requirement and to fulfill this requirement developer prefer to buy country database or web service or if cost issue then they manually creates country database but we don't require to follow these lengthy process since C# globalization class is capable to display the country list around 144 which is enough if requirement is not wast.
Now let's start creating a simple MVC  application to demonstrate how to get list of countries without database in ASP.NET MVC using globalization class
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,

Step 2: 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 Home with suffix Controller.
Now modify the default code in HomeController.cs class file and create the action methods, after modifying the code will look like as follows,
HomeController.cs
 
using System.Collections.Generic;
using System.Globalization;
using System.Web.Mvc;

namespace DisplayCountryList.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            List<string> CountryList = new List<string>() ;
            CultureInfo[] CInfoList = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
            foreach (CultureInfo CInfo in CInfoList)
            {
                RegionInfo R = new RegionInfo(CInfo.LCID);
                if (!(CountryList.Contains(R.EnglishName)))
                {
                    CountryList.Add(R.EnglishName);
                }
            }

            CountryList.Sort();
            ViewBag.CountryList = CountryList;
            return View();
        }
    }
}

Step 3: Create View

Right click on view folder or near Index Action method and Add view with name Index and modify the existing view code , After modifying the code the Index.cshtml will be look like as follows

@{
    ViewBag.Title = "www.compilemode.com";
}
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <hr />
        <div class="form-group">
            <label class="col-md-2 control-label">Select Country</label>
            <div class="col-md-10">
                @Html.DropDownList("CountryList",new SelectList(ViewBag.CountryList),new {@class = "form-control" })
            </div>
        </div>

        
    </div>
}

In the preceding code snippet we are binding DropDownList with ViewBag in which country list is assigned into the controller class.
Step 4: Run application
 Now run the application we will see dropdownlist having list of countries as shown in the following screen shot


Now Expand dropdownlist to see the other counties as shown in the following screen shot


I hope from all the preceding examples,  you learned how to display country list without Database 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.
  • It will not display all county list but its shows list major around 144 countries .
Summary
I hope this article is useful for all readers, If you have a suggestion then please contact me.
Don't Forget To 

Multiple Layout Pages In ASP.NET MVC

Layout page shares the common design across all pages. It is similar to master page in ASP.NET. There are many methods which are listed below to change the layout page dynamically in ASP.NET MVC  
  • While Adding View Page, Assign Layout Page .
  • Using View Start Page
I hope you have understand about the Layout page from preceding brief summary. Now let's implement it practically.
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 user and admin controller 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 the following window appears,
 
Now specify the controller name and click on add button then the UserController class will be added into the application , now follow the same steps and add the AdminController class,
After adding the two controller the solution explorer will be like the following,
 
The preceding two controller classes are added into the project which are User and Admin and create the following action methods in respective controller class.
UserController.cs
public class UserController : Controller  
    {  
        public ActionResult Login()  
        {  
            //write logic here  
            return View();  
        }  
    } 
AdminController.cs
public class AdminController : Controller  
   {  
       [HttpPost]  
       public ActionResult AddRole()  
       {  
           //write logic here  
           return View();  
       }  
   } 
For preceding two controllers we will use two different layout pages.
Step 3: Add Views and Layout pages
We can decide which layout page to be used while adding the view. IIt is same as deciding master page while adding ASP.NET web page. Let us follow the following steps to add layout page with view.
Click on View folder of created MVC application as,

As shown in preceding image, specify view name and check on use layout page option and click on add button then the following default layout page will be added into the solution explorer as,
The above is default layout page and will be added into the solution explorer. Now lets add another layout page named admin as in the following. Click on solution explorer and add layout page as,
Now click on add button, then added layout pages will look like as follows,

In the preceding image, two layout pages are added under shared folder which are AdminLayoutPage and Layout.
Step 4: Set layout pages to view
We have created view and layout pages. Now let us assign layout pages to the views. There are many ways to assign layout page to the view which are listed as in the following:
  • Using wizard
  • Using ViewStart page
  • Using view method
Using wizard
You can use wizard to set the layout page while adding the view, steps are as follows:
  • Right click on view folder and select view template as,

Specify the view name and check on Use a layout page and click on browse button. The following window will appear,

Now choose layout page from preceding available Layout pages and click on ok button. The layout page will  look like as follows,

Now click on add button then layout page reference added into the view page as,
 
So whenever you will add through wizard or manually the layout page reference need to be set in every view page where the layout page is needed.
Using ViewStart page
Adding reference of layout page in every page is very difficult and repetitive of code. Let us consider I have one controller which as twenty plus action method then each twenty views we need to add reference of layout page. Assume another requirement we need to set layout page according to condition basic or controller basic then we need to use viewstart page .
So lets open the ViewStart.cshtm page and write the following code,
@{  
    string CurrentName = Convert.ToString(HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"]);  
    dynamic Layout;  
    switch (CurrentName)  
    {  
        case "User":  
            Layout = "~/Views/Shared/_Layout.cshtml";  
            break;  
        default:  
            //Admin layout  
            Layout = "~/Views/Shared/_AdminLayoutPage.cshtml";  
            break;  
    }  
}  
Now run the application, the Login view will  look like as follows in which we have used Layout page,
Now run AddRole view, Then the output will look like the following,
 
I hope from all the preceding examples, you have learned about layout pages in ASP.NET MVC.
Note:
  • Download the Zip file of the sample application for a better understanding.
  • Apply proper validation before using it in your project.
Summary
I hope this article is useful for all readers. If you have any suggestions, then please mention it in the comment section.

How To Use Multiple Buttons on Single View In ASP.NET MVC

There are many scenarios where we need multiple submit buttons on single view but in this example we are considering the scenario in which we have one view from where the user can add the employee details and if the details are not sufficient then the user can save it as a draft. Now let's start creating a simple MVC application to demonstrate the above scenario.
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,

Step 2: Create Model Class

Now let us create the model class file named EmployeeModel.cs by right clicking on model folder as in the following screenshot,

Note

It is not mandatory that Model class should be in Models 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 names or without folder name or in a separate class library.

EmployeeModel.cs class file code snippet
using System.ComponentModel.DataAnnotations;  
  
namespace ManagningMultipleSubmitButtonsInMVC.Models  
{  
    public class EmployeeModel  
    {  
        [Required]  
        public string Name { get; set; }  
        [Required]  
        public string City { get; set; }  
       
        public string Address { get; set; }  
    }  
}  
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 Home with suffix Controller.
Note

The controller name must have a suffix as 'Controller' after specifying the name of the controller. Now modify the default code in HomeController.cs class file and create two action methods, after modifying the code will look like as follows,
HomeController.cs
using ManagningMultipleSubmitButtonsInMVC.Models;  
using System.Web.Mvc;  
  
namespace ManagningMultipleSubmitButtonsInMVC.Controllers  
{  
    public class HomeController : Controller  
    {  
          
        public ActionResult Employee()  
        {  
            return View();  
        }  
        [HttpPost]  
        public ActionResult Save(EmployeeModel objSave)  
        {  
  
            ViewBag.Msg = "Details saved successfully.";  
            return View();  
        }  
        [HttpPost]  
        public ActionResult Draft(EmployeeModel objDraft)  
        {  
            ViewBag.Msg = "Details saved as draft.";  
            return View();  
        }  
  
    }  
}  
In the preceding code sample, we have two action methods named Save and Draft Save action method is used to save the records and Draft is used to save the details as draft for saving later.

Step 4: Create View

Now let's create strongly typed view named Employee from EmployeeModel class ,

Click on Add button then it will create the view named Employee, Now open the Employee.cshtml view, then some default code you will see which is generated by MVC scaffolding template, now modify default code to make as per our requirements. After modifying the code it will look like as in the following,
@model ManagningMultipleSubmitButtonsInMVC.Models.EmployeeModel  
  
@{  
    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.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-12">  
                <input type="submit" value="Save" class="btn btn-primary" />  
                <input type="submit" value="Draft" class="btn btn-primary" />  
  
            </div>  
              
        </div>  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
               @ViewBag.Msg  
  
            </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> 
Now after adding the Model, add View and controller into our project. The solution explorer will look like as follows,

Step 5 : Now run the application and click on any one of the buttons,  it will fire only Save action method as,

In the preceding screen shot, if we clicked on any one of the buttons it will point to the save action method because we have only one form and two submit buttons, so it's not possible to point to two different buttons on two different action methods usingthe preceding scenario.

Step 6 :Solution

There are lots of solutions to solve the preceding issue, we will look at the one which requires the least effort to solve the same scenario:
  • By creating two forms on single view by using html.Action helper class
  • By changing input type submit button of those submit buttons but the model validation will not be fired .
  • By Using javascript or jQuery to submit forms but default validations will not work.
  • By using action name along with name property in submit button.
  • By Using formaction property of submit button,
So in this article we will use a simple way by formation of name property of submit button:

In the preceding example we have provided the ActionResult method name in formation property of submit button, now let's update the Employee.cshtml view code; after updating the code; the Employee.cshtml code will look like as follows
@model ManagningMultipleSubmitButtonsInMVC.Models.EmployeeModel  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
@using (Html.BeginForm("Save","Home",FormMethod.Post))   
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">  
          
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-12">  
  
  
                <input type="submit" value="Save" formaction="Save"  class="btn btn-primary" />  
  
                <input type="submit" value="Draft"  formaction="Draft" class="btn btn-primary" />  
  
            </div>  
              
        </div>  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10 text-success">  
                @ViewBag.Msg  
                
  
            </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>
Step 7: Now let's run the application and click on the save button, then it will fire the save action method as,

Now click on draft button, it will fire the Draft action method and  show the following message,
 I hope from all the preceding examples we have learned how to use multiple submit buttons on single view in ASP.NET MVC.
Note
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
Summary
I hope this article is useful for all readers. If you have any suggestions please contact me.

Video : Creating ASP.NET Web Service Using Visual Studio 2015

This Video tutorial explain how to Create ASP.NET Web Service Step by Step which covers the following topics
  • Why Web Service?
  • What Is Web Service?
  • Real Time Scenario 
  • Creating ASP.NET Web Service Using VS 2015
  • Creating Web Method 
  • What is Web Method?
  • Understanding WSDL 
  • Understanding SOAP Request and Response Header 
  • Testing Web Service output on browser

Don't Forget To 

Summary
I hope this video tutorial is useful for all readers. If you have any suggestion then please contact me.

Sending Emails in ASP.NET MVC

Email communication is very important in today's modern applications and there are many ways to send emails through applications to users. I wrote a series of articles on email sending in ASP.NET which is very successful series in terms of views and downloads. Now in this article we will learn how to send emails directly from razor view in ASP.NET MVC with the help of WebMail helper class . So let's learn step by step so beginners can also learn how to send emails in ASP.NET MVC.
What is WebMail Helper Class?
WebMail is the static class which is  used to send emails directly from  Razor view as well controller class in ASP.NET MVC .
Prerequisites
  • Active internet connection.
  • Email id of any provider such as Gmail, Yahoo or your organization to send emails. 
Now let's create a simple MVC application to demonstrate this.
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:
 3. 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 whose Solution Explorer will look like the following:

Step 2: Create Model Class.
Now let us create the model class named EmployeeModel.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 names or without folder name or in a separate class library.
EmployeeModel.cs class code snippet:
using System.ComponentModel.DataAnnotations;  
  
namespace SendingEmailsWithWebMailInMVC.Models  
{  
    public class EmployeeModel  
    {          
         
        [DataType(DataType.EmailAddress),Display(Name ="To")]  
        [Required]  
        public string ToEmail { get; set; }  
        [Display(Name ="Body")]  
        [DataType(DataType.MultilineText)]  
        public string EMailBody { get; set; }  
        [Display(Name ="Subject")]  
        public string EmailSubject { get; set; }  
        [DataType(DataType.EmailAddress)]  
        [Display(Name ="CC")]  
        public string EmailCC { get; set; }  
        [DataType(DataType.EmailAddress)]  
        [Display(Name ="BCC")]  
        public string EmailBCC { get; set; }  
    }  
}  
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 Home with suffix Controller.
Note:
The controller name must be having suffix as 'Controller' after specifying the name of controller. Now the default code in HomeController.cs will look like as follows,
HomeController.cs
using System.Web.Mvc;  
namespace SendingEmailsWithWebMailInMVC.Controllers  
{  
    public class HomeController : Controller  
    {  
        // GET: Index view  
        public ActionResult Index()  
        {             
            return View();  
        }  
  
        [HttpPost]  
          
        public ActionResult SendEmailView()  
        {  
            //call SendEmailView view to invoke webmail  
            return View();  
        }  
    }  
}  
Step 4 : Creating strongly typed view named Index using employee model and SendEmailView .
Right click on View folder of created application and choose add view , select employee model class and scaffolding create template to create view to send emails
 Now open the Index.cshtml view , Then following default code you will see which is generated by MVC scaffolding template as,
Index.cshtml
@model SendingEmailsWithWebMailInMVC.Models.EmployeeModel  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
@*Send request to invoke SendEmailView view*@  
@using (Html.BeginForm("SendEmailView","Home",FormMethod.Post))   
{  
    @Html.AntiForgeryToken()  
    <div class="form-horizontal">      
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.ToEmail, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.ToEmail, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.ToEmail, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.EMailBody, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.EMailBody, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.EMailBody, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.EmailSubject, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.EmailSubject, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.EmailSubject, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.EmailCC, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.EmailCC, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.EmailCC, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.EmailBCC, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.EmailBCC, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.EmailBCC, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Send" class="btn btn-default" />  
            </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>  
The preceding view is used to Get the Input email details from users , Now create the view named SendEmailView to configure the emails using WebMail class.
SendEmailView.cshtml

@{  
    ViewBag.Title = "www.compilemode.com";  
}  
  
  @{  
      try  
      {  
          //parameters to send email  
          string ToEmail, FromOrSenderEmail = "YourGamilId@gmail.com", SubJect, Body, cc, Bcc;  
  
          //Reading values from form collection (Querystring) and assigning values to parameters  
          ToEmail = Request["ToEmail"].ToString();  
          SubJect = Request["EmailSubject"].ToString();  
          Body = Request["EMailBody"].ToString();  
          cc = Request["EmailCC"].ToString();  
          Bcc = Request["EmailBCC"].ToString();  
          //Configuring webMail class to send emails  
          WebMail.SmtpServer = "smtp.gmail.com"; //gmail smtp server  
          WebMail.SmtpPort = 587; //gmail port to send emails  
          WebMail.SmtpUseDefaultCredentials = true;  
          WebMail.EnableSsl = true; //sending emails with secure protocol  
          WebMail.UserName = FromOrSenderEmail;//EmailId used to send emails from application  
          WebMail.Password = "YourGmailPassword";  
          WebMail.From = FromOrSenderEmail; //email sender email address.  
  
          //Sending email  
          WebMail.Send(to: ToEmail, subject: SubJect, body: Body, cc: cc, bcc: Bcc, isBodyHtml: true);  
        <hr />  
        <div class="text-success">  
            Email Sent Successfully.  
        </div>  
      }  
      catch (Exception)  
      {  
        <div class="text-danger">  
            Problem while sending email, please check gmail server details.  
        </div>  
      }  
}  
Now after adding the model , view and controller our application solution explorer will look as follows,

Now we have done all coding to send emails using WebMail class .
Step 5 : Now run the application.
After running the application initial screen will look as follows,
The preceding view is used to send the emails , now click on send button without entering To email address and invalid cc and Bcc email address it throws the following errors .
 Now Enter the valid details as follows,
Now click on Send button it will redirect to the SendEmailView invoked the WebEmail class and send the email , after successfully sending the email the following message will be shown,
Now open the your gmail inbox and see the details which we have used to send the email as,
 Now open the email , It will show the email content as follows,

I hope from all the preceding examples we have learned how to send email using WebMail helper class in ASP.NET MVC Razor view .

Note:

  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
  • This application is created completely focusing on beginners.
  • You need an active internet connection to send the email .
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:

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 

    www.CodeNirvana.in

    Protected by Copyscape Online Copyright Protection
    Copyright © Compile Mode