Allow Multiple GET POST Methods in Single ASP.NET Web API Controller

Many reader asking me, How we use multiple GET, POST , PUT , Delete methods in single Web API Controller class since , If we are going use multiple POST or GET methods in single API controller then its not working . So by considering this requirement I have decided to write article to explain why multiple Get , Post methods are not working and what configuration we need to do So we can use multiple Get , POST methods in single Web API controller class.
Problem
The default URL structure of ASP.NET Web API defined into the WebApiConfig.cs file is like shown in the following Image.


In the Preceding routing structure, we can access the resource using Base url+API+ApiController which is by default defined in WebApiConfig.cs due of this reason all resources accessed using controller name because inside the controller not more than one method defined which having same HTTP verb like GET or POST . We can access the web API methods using following url structure with this default routing pattern .
 Consider our REST Service URL will be http://localhost:56290/api/Home which is described as follows,
  • http://localhost:56290: Is the base address of web API service, It can be different as per your server.
  • API: It is the used to differentiate between Web API controller and MVC controller request .
  • Home: This is the Web API controller name.
Once we add another POST or Get method inside the API controller class with same url routing structure then while accessing the specific method is very difficult due to the ambiguity between the two same HTTP verb method .
Solution
To overcome the preceding mentioned issue and allow multiple GET , POST methods in single web API controller class then you need to modify url structure which is defined inside the WebApiConfig.cs as shown in the following Image .

Now with preceding url pattern we can access web API methods base url +API+Controller+webApi method.
E.g
http://localhost:56290/api/Home/AddEmployeeDetails 
From all preceding examples and explanations we have learned how to use multiple GET POST methods in single web API controller class.
Summary
I hope this article is useful for all readers. If you have any suggestions, then please mention it in the comment section.

Uploading Multiple Files In ASP.NET MVC Using HttpPostedFileBase

Many times, we need to upload multiple files at a time in an Application, instead of one by one, to save the user time, which is required for a particular process. There are many ways to upload multiple files in ASP.NET MVC, but in this article, we will use HttpPostedFileBase MVC class to upload the multiple files, instead of any script like jQuery or JavaScript. Lets start implementing this scenario, step by step with the help of a simple ASP.NET Application. Thus, the beginners and students can understand easily.
Step 1: Create an MVC Application.
Now, let us start with a step by step approach from the creation of a simple MVC Application in the following:
  1. "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
  2. Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", 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, named FileModel.cs, by right clicking on Models folder, as shown in the screenshot, given below:
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 the folder name or in a separate class library.
FileModel.cs class code snippet,
using System.ComponentModel.DataAnnotations;  
using System.Web;  
  
namespace UploadMultipleFilesInMVC.Models  
{  
    public class FileModel  
    {  
        [Required(ErrorMessage ="Please select file.")]  
        [Display(Name ="Browse File")]  
        public HttpPostedFileBase[] files { get; set; }  
         
    }  
}  
In the preceding code snippet, we are using HttpPostedFileBase, which is the easiest way to read the uploaded files and pass to the controller.
Step 3 : Add Controller Class

Now, let us add ASP.NET MVC controller, as shown in the screenshot, given below:

After clicking Add button, it will show the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller to upload the multiple files. After modifying the code of Homecontroller class, the code will look like:
HomeController.cs
using System.IO;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
  
namespace UploadMultipleFilesInMVC.Controllers  
{  
    public class HomeController : Controller  
    {  
        // GET: Home  
        public ActionResult UploadFiles()  
        {  
            return View();  
        }  
        [HttpPost]  
        public ActionResult UploadFiles(HttpPostedFileBase[] files)  
        {  
  
            //Ensure model state is valid  
            if (ModelState.IsValid)  
            {   //iterating through multiple file collection   
                foreach (HttpPostedFileBase file in files)  
                {  
                    //Checking file is available to save.  
                    if (file != null)  
                    {  
                        var InputFileName = Path.GetFileName(file.FileName);  
                        var ServerSavePath = Path.Combine(Server.MapPath("~/UploadedFiles/") + InputFileName);  
                        //Save file to server folder  
                        file.SaveAs(ServerSavePath);  
                        //assigning file uploaded status to ViewBag for showing message to user.  
                        ViewBag.UploadStatus = files.Count().ToString() + " files uploaded successfully.";  
                    }  
   
                }  
            }  
            return View();  
        }  
    }  
}  
Step 4 : Creating strongly typed view
Right click on View folder of the created Application and choose add view, select FileModel class along with creating scaffolding template to create the strongly typed view to upload the multiple files as: 

Click Add button and it will create the view named UploadFiles. Now, open the UploadFiles.cshtml view, change the default code, as per requirement to upload the multiple files, which is generated by MVC scaffolding template as:

UploadFiles.cshtml
@model UploadMultipleFilesInMVC.Models.FileModel  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
  
@using (Html.BeginForm("UploadFiles", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
{  
    @Html.AntiForgeryToken()  
  
    <div class="form-horizontal">  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.files, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })  
                @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit"  value="Upload" class="btn btn-primary" />  
            </div>  
        </div>  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10 text-success">  
                @ViewBag.UploadStatus  
            </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 5 : Create a folder named UploadedFiles or as you wish to save uploaded files
Right click on the created ASP.NET MVC Application, Solution Explorer and choose add new item, Add New Folder. After adding the model, view, controller and UploadedFiles folder, Solution explorer will look like:
Now, we have done all the coding to upload the files.
Step 6: Run the Application.
After running the application, click upload button without selecting the file. It will show the following error message, which is set in created FileModel class as:
Now, browse the file from your machine hard disc location or any other storage device, which is connected to the machine and select one by one files by pressing a control key or if you want to select the multiple files, press Ctrl+A keys, as shown in the screenshot, given below:
Now, after selecting the multiple files, click upload button and it will show the following message after uploading the files as:

 Now, let's ensure our uploaded files are uploaded to the Server folder by browsing the Server folder location, which is used to save the uploaded files. After browsing the Server folder, the uploaded files will be located as follows:


I hope from all the preceding examples and explanations  we have learned how to upload multiple files in ASP.NET MVC . 
Note

  • HttpPostedFileBase instance name must be a same as file uploader control name.
  • Its important to define enctype = "multipart/form-data" in form action, else the value will be null in the controller .
  • Download the Zip file of the sample Application for a better understanding.
  • Since this is a demo, it might not be using proper standards. Thus, improve it, depending on your skills.
Summary
I hope uploading multiple files in ASP.NET MVC article is useful for all the readers to upload the multiple files in ASP.NET MVC. If you have any suggestions, please contact me.

Read more articles on ASP.NET:

Comma Separated Auto Complete TextBox In ASP.NET MVC Using jQuery JSON

Many times, we need to add comma separated values in a text box from autocomplete TextBox to fulfill the particular requirement.  Let's say, we have one page to send the emails. Then consider, we want to send emails to multiple recipients with cc and emails Id's from coming from database using autocomplete TextBox. In this type of scenario, we need a comma separated autocomplete TextBox .Let's start implementing this scenario by creating one simple ASP.NET MVC application, step by step .
Step 1: Create ASP.NET MVC Application
  1. Go to "Start" --> "All Programs"  --> select "Microsoft Visual Studio 2015".
  2. Go to "File" --> "New" --> click "Project" --> 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 "Models" folder, as in the following screenshot:


Now, the EmployeeModel.cs class file code snippet will look like this:
EmployeeModel.cs 
using System.ComponentModel.DataAnnotations;  
namespace CommaSepratedAutoCompleteTextBox.Models  
{  
    public class EmployeeModel  
    {  
        public int EmpId { get; set; }  
        public string EmpName { get; set; }  
  
    }  
}  
Step 3: Add Controller Class
Now, 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'.
Now, modify the default code in HomeController.cs class file and create two action methods, after modifying the code will look like as the following:
using CommaSepratedAutoCompleteTextBox.Models;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web.Mvc;  
  
namespace CommaSepratedAutoCompleteTextBox.Controllers  
{  
    public class HomeController : Controller  
    {  
  
        // GET: Home  
        public ActionResult EmpoyeeDetails()  
        {  
            return View();  
        }  
  
  
        [HttpPost]  
        public JsonResult GetAutoEmpName(string Prefix)  
        {  
  
            //Adding list of records into list  
            List<EmployeeModel> ObjList = new List<EmployeeModel>()  
            {  
                new EmployeeModel {EmpId=1,EmpName="Vithal Wadje" },  
                new EmployeeModel {EmpId=2,EmpName="Suhir Wadje" },  
                new EmployeeModel {EmpId=3,EmpName="Anil Kumar" },  
                new EmployeeModel {EmpId=4,EmpName="Ravi" },  
                new EmployeeModel {EmpId=5,EmpName="Ramesh s" },  
                new EmployeeModel {EmpId=6,EmpName="Sachin Y" },  
                new EmployeeModel {EmpId=7,EmpName="Vikran T"},  
                  
  
        };  
            //Searching records from list using LINQ query.   
            var EmpName = (from e in ObjList  
                            where e.EmpName.ToLower().StartsWith(Prefix.ToLower())  
                           select new { e.EmpName });  
            return Json(EmpName, JsonRequestBehavior.AllowGet);  
        }  
  
    }  
}  
In the preceding 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. We can get same records from database as well.
Step 4: Add Reference of  jQuery UI CSS and JS library
There are many ways to add the reference of jQuery library into our project. The following are some methods:
  1. Using NuGet package manager, you can install library and reference into the project.
  2. Use CDN library provided by Microsoft, jQuery, Google or any other which requires active internet connection.
  3. Download jQuery files from jQuery official website and reference into the project.
In the preceding procedure of adding references of libraries into the project, 1 & 3 steps don't require the active internet connection but if you are following second step, it requires active internet connection to load the CDN library's references into the project .
In this example, I have followed the third step to add the jQuery UI libraries references. Now, open the Layout.cshtml page to add the references. The Layout.cshtml page's header section will be look like:
Layout.cshtml
@*Uncomment following lines, If you wants to use CDN jquery-ui.css and jquery-ui.js*@  
   @*<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">*@  
   @*<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>*@  
     
   <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
   <link href="~/Content/jquery-ui.css" rel="stylesheet" />  
   <script src="~/Scripts/jquery-ui.js"></script> 
Step 5: Create jQuery Ajax function.
To call controller JSON action method and invoke autocomplete function including for comma separated search text, write the following jQuery function .
<script type="text/javascript">  
  
    $(document).ready(function () {  
  
         
        $("#EmpName").autocomplete({  
            source: function (req, resp) {  
                $.ajax({  
                    url: "/Home/GetAutoEmpName",  
                    type: "POST",  
                    dataType: "json",  
                    data: { Prefix: GetCurrentSearchTerm(req.term) },  
                    success: function (data) {  
                        resp($.map(data, function (item) {  
                            return { label: item.EmpName, value: item.EmpName };  
                        }))  
  
                    }  
                })  
            },  
            
            select: function (event, ui) {  
                var LastValue = splitCurrentText(this.value);                
                LastValue.pop();  
                LastValue.push(ui.item.value);  
                LastValue.push("");  
                this.value = LastValue.join(",");  
                return false;  
            },  
            focus: function () {  
            return false;  
        }  
        });  
        function splitCurrentText(LastTerm) {  
  
            return LastTerm.split(/,\s*/);  
        }  
  
        function GetCurrentSearchTerm(LastTerm) {  
  
            return splitCurrentText(LastTerm).pop();  
        }  
    });  
</script>  
Note: To work preceding function, don't forget to add the reference of the following jQuery UI libraries into the project by CDN or by downloading.
Step 6: Create View
Now, let's create Strongly Typed View named EmployeeDetails from EmployeeModel class.



After adding the necessary code, files, and logic, the EmployeeDetails .cshtml will look like the following:

@model CommaSepratedAutoCompleteTextBox.Models.EmployeeModel  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
<script type="text/javascript">  
  
    $(document).ready(function () {  
  
         
        $("#EmpName").autocomplete({  
            source: function (req, resp) {  
                $.ajax({  
                    url: "/Home/GetAutoEmpName",  
                    type: "POST",  
                    dataType: "json",  
                    data: { Prefix: GetCurrentSearchTerm(req.term) },  
                    success: function (data) {  
                        resp($.map(data, function (item) {  
                            return { label: item.EmpName, value: item.EmpName };  
                        }))  
  
                    }  
                })  
            },  
            
            select: function (event, ui) {  
                var LastValue = splitCurrentText(this.value);                
                LastValue.pop();  
                LastValue.push(ui.item.value);  
                LastValue.push("");  
                this.value = LastValue.join(",");  
                return false;  
            },  
            focus: function () {  
            return false;  
        }  
        });  
        function splitCurrentText(LastTerm) {  
  
            return LastTerm.split(/,\s*/);  
        }  
  
        function GetCurrentSearchTerm(LastTerm) {  
  
            return splitCurrentText(LastTerm).pop();  
        }  
    });  
</script>  
  
@using (Html.BeginForm())   
{    
    <div class="form-horizontal">  
     <hr />  
        <div class="form-group">  
              
            <div class="col-md-10">  
                @Html.EditorFor(model => model.EmpName, new { htmlAttributes = new { @class = "form-control" } })  
            </div>  
        </div>  
  
    </div>  
}  

Now, run the application. Type any word and it will auto populate the records which exactly start with the first word, as in the following screenshot:


Now, after selecting the particular records, it is added into TextBox with comma. Now, type another initial letter and it will popup the list of records.



Now, add multiple records with commas. The TextBox will look like as follows.

From all preceding examples and explanation, I hope you learned how to create the comma separated auto complete TextBox using jQuery UI in ASP.NET MVC.
Note
  • Since this is a demo, it might not be using proper standards. So, improve it according to your skills.
Summary
I hope this article is useful for all the readers. If you have any suggestions, please contact me.
Read more articles on ASP.NET MVC

Disable Future And Past Date of jQuery Calendar In ASP.NET MVC

In any application validation is very important to avoid invalid data being inserted into the database which sometimes breaks the business process . Any booking system the date is very important, Consider an example, I have online ticket booking system such as BUS and what is happen if I allow past date and user booked the ticket of past date then what will be happen just Imagine .So by considering these type of business requirement I have decided to write this article which disable the past and future dates of calendar control as per our requirement.. So let us implement this requirement step by step,
  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 EmpModel and write the following line of code,
EmpModel.cs
public class EmpModel    
{   
   [Display(Name ="Enter Date")]    
   public DateTime EnterDate { get; set; }    
} 
Step 3: Home controller

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


Now after selecting controller template, click on add button then the following window appears,



Specify the controller name and click on Add button,

HomeController.cs
public class HomeController : Controller    
{    
    // GET: Home    
    public ActionResult Index()    
    {    
        return View();    
    }    
}   
In the above code, The only action result method named Index handle the user request when the user request for the view named Index.cshtml which will be added later .

Step 4: Reference jQuery UI.

Reference jQuery UI css and js library reference as there are many ways to add the reference of jQuery library into 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.

 As we know how to use jQuery UI calendar we need to use datepicker function and to set or allow specific date range in calendar we need to use the following properties of datepicker function,
  • yearRange: It sets the year range for calendar control such as how many past and future years to display in calendar.
  • minDate :  It sets the minimum date for calendar control .
  • maxDate : it sets the maximum date range for calendar control .
Step 5: Create jQuery function to invoke datepicker function,
$(document).ready(function() {  
    $("#EnterDate").datepicker({  
        dateFormat:"dd-mm-yy",  
        minDate: -0,  
        maxDate: "+0M +0D"  
  
    });  
});
For making the above function yo work 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.

Add strongly typed view named index from EmpModel class as,



After adding necessary code, files and logic the Index.cshtml code will look like the following,

Index.cshtml
@model DissablePastandFutureDateInMVC.Models.EmpModel  
  
@{  
    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>  
  
  $(document).ready(function() {  
      $("#EnterDate").datepicker({  
          dateFormat:"dd-mm-yy",  
          minDate: -0,  
          maxDate: "+0M +0D"  
  
      });  
  });  
</script>   
  
  
@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.EnterDate, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.EnterDate, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.EnterDate, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        
    </div>  
}  
Now run the application and put mouse pointer into the textbox the calendar control will popup as in the following screenshot,
 
In the above screenshot you can see that only current date is enabled and all other dates are disabled. Now let us change the maxDate property to enable only five days from current date,
$(document).ready(function() {  
    $("#EnterDate").datepicker({  
        dateFormat:"dd-mm-yy",  
        minDate: -0,  
        maxDate: "+0M +4D"  
  
    });  
}); 
Now run the application the output will be as follows:
 
In the preceding screenshot you can see that only five dates are available including current date. From all the preceding examples, I hope you learned how to disable past and future dates using jQuery UI calendar control in ASP.NET MVC.

Note:
  • For the detailed code, please download the sample zip file.
  • You need to use the jQuery library and if you are using CDN library then it requires active internet connection .
Summary

I hope this article is useful for all readers. If you have a suggestion then please contact me.

Sending Emails In ASP.NET MVC Using WebMail Class

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:

Getting Started With WCF Service

WCF stands for windows communication platform which is used to communicate with cross Platform application and to develop network distributed application.
Previously WCF was knows Indigo service and later on with .Net Framework its knows as WCF, WCF was first introduced with .Net Framework 3.0 in 2006 later on its become the most popular programming language for network distributed application because it provides all combined features of Web service, Remoting, MSMQ and com+ on single platform without using different service for different requirement.
Download Aspose : API To Create and Convert Files
Let us understand with following Diagram


From above diagram, I am trying to give you message that WCF is the common technology to provide the feature of all technologies being used to communicate for different purposes.
Why WCF ?
WCF Provides the wide range of feature including communication protocol support, Security and so on let us considers the following example.

This is normal communication of Web service and client in which client requirement is to exchange the data using HTTP Protocol.
In the above example Web service communicate with client using HTPP protocol and only HTTP protocol supports web service and suppose in future client wants to exchange data using TCP as wel as HTTP without creating a separate service then with Web service its not possible ,we can achieve it by using WCF service.

from the above diagram i am trying to explain that WCF Service can exchange data or message in any format that is SOAP,Binary using wide range of communication protocol such as HTTP ,TCP and so on.

WCF Architecture 
The WCF architecture consists of following components
  • Contracts.
  • Service Run time.
  • Messaging.
  • Activation and Hosting .
Let us briefly learn about them

Contracts in WCF

Contracts are useful to built the WCF service application .Contracts defines what protocol (binding) does service use ,how communication will be done ,what message exchange format to use and much.
The following are the Contracts which are available in WCF
  • Service contracts
  • Data contracts
  • Message contracts
  • Fault Contract 
  • Operation contract
  • Policies and Binding
Service contracts
Service contracts nothing but the it defines the Interface for the service.It can be defined as follows
Syntax
   [ServiceContract]
    public interface IService1
    {

        // TODO: Add your service operations here
    }
Operation contract
Operation contract defines the method which is exposed to the client to exchange the information between client and server.Operation contract describes the what functionality to be given to the client such as Addition, subtraction etc
It can be defined as
   public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);
  
    }
Data Contract
Data Contracts are same as get set properties but difference is that data contract in WCF is used to serialize and deserialize the complex data.it defines how data types are serialized and deserialized. Through serialization, you convert an object into a sequence of bytes that can be transmitted over a network. Through de-serialization, you reassemble an object from a sequence of bytes that you receive from a calling application.
It can be defined as follows 
    [DataContract]
    public class Student
    {
        private string _Name;

        private string _City;


        [DataMember]
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
}
Fault Contract
Fault contract is used to handle the exception and know the cause of error which is occur in WCF service, basically when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handling are technology specific.
In order to support interoperability and client will also be interested only, what went wrong? Not on how and where cause the error.
The following is the syntax to raise the custom error in WCF
[ServiceContract]
    public interface IGetDetailsService
    {
        [OperationContract]
        [FaultContract(typeof(Student))]
        Student GetDetails(string Name);
    }

    [DataContract]
    public class Student
    {
        private string _Name;

        private string _City;

        [DataMember]
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        [DataMember]
        public string City
        {
            get { return _City; }
            set { _City = value; }
         }
}
Message contracts
Default SOAP message format is provided by the WCF run time for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.
It can be defined as
[MessageContract]
public class Person
{
  [MessageHeader] public Operation Name;
  [MessageHeader] public string city;
  [MessageBodyMember] private Home Address;
  [MessageBodyMember] private Home Streat;
  [MessageBodyMember] public int age;
}
Policies and Binding in WCF
Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding
Service Run-time in WCF
It contains the behaviors that occur during run-time of service.The following behaviors managed by service run-time layer.
  1. Throttling Behavior
  2. Error Behavior 
  3. Metadata Behavior
  4. Instance Behavior 
  5. Transaction Behavior
  6. Dispatch Behavior 
  7. Concurrency Behavior
  8. Parameter filtering
  9. Message inspection
  • Throttling Behavior- Controls how many messages are processed.
  • Error Behavior - Specifies what occurs, when internal error occurs on the service.
  • Metadata Behavior - Tells how and whether metadata is available to outside world.
  • Instance Behavior - Specifies how many instance of the service has to be created while running.
  • Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.
  • Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.
  • Concurrency Behavior-Its used to control how many threads can access a given instance of service. 
  • Parameter filtering-It filters the message headers and executes preset actions based on the filters of the message headers. 
  • Message inspection-Its used to inspect specific part or all parts of  the message through service.
 Messaging in WCF Service
Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as
  1. Transport Channels
  2. Protocol Channels  
Transport Channels 
Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.
Protocol Channels
Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

Activation and Hosting in WCF

Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism
IIS
Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
Windows Activation Service
(WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
Self-Hosting
WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.
Windows Service
WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM)
Advantages of WCF
  1. Support for different protocol
  2. Security over transport as well as Message level
  3. Easy to implement MSMQ and REST Service.
  4. Load balancing & support scaling.
  5. It can control concurrency.
  6. It can be hosted on IIS, WAS, Self hosting, Windows services.
  7. Multiple Message Patterns.
  8. Unhanded Exceptions does not return to the client as SOAP faults. WCF supports better exception handling by using Fault Contract.
Note
Please refer my following articles for complete understanding
Summary
I hope this article is useful for all students and beginners. If you have any suggestion related to this article then please contact me.
Download Aspose : API To Create and Convert Files

www.CodeNirvana.in

Protected by Copyscape Online Copyright Protection
Copyright © Compile Mode