Recap of My Speaking at National University of Singapore on Microsoft Azure IaaS Using ASP.NET Core

I was recently visited to National University of Singapore on ‎January ‎07- 2017, NUS has very huge and world class campus with latest infrastructure, It was great pleasure to meet world class students from all over the world , Many students came up with great start up ideas and to boost their start up ideas I have extended my support to help them at free of cost to turn their ideas into reality .

I was got opportunity to explain How Microsoft Azure helps startups to manage their application with less infrastructure cost without buying physical servers , I have explained real time example of Microsoft azure with ASP.NET Core


Addressing group of students on Microsoft Azure Infrastructure as service (IaaS) using ASP.NET Core




 Following is the group photo with few students who led the event


It was great and proud moment for me thanks to all my readers and community for great support. If you wants to invite to me to your any technical or career guidance related college event then you can contact me anytime , for my latest speaking visit Vithal Wadje Speaking  section
Don't Forget To 

Uploading Downloading PDF Files From DataBase In ASP.NET MVC

Many times, we need to work with the file and storing the physical files on the Server, which is very difficult because it will consume lots of physical hard disc space of the Server. Thus, in this article, we will learn, how to upload and download the files directly from the database in ASP.NET MVC. Thus, let's learn step by step so the beginners can also understand.
Step 1 - Create 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 file, named EmpModel.cs, by right clicking on Models folder and define the following properties in EmpModel.cs class and FileDetailsModel as:
The code snippet of EmpModel.cs and FileDetailsModel .cs will look like-
public class EmpModel  
   {  
       [Required]  
       [DataType(DataType.Upload)]  
       [Display(Name ="Select File")]  
       public HttpPostedFileBase files { get; set; }  
   }  
  
   public class FileDetailsModel  
   {  
       public int Id { get; set; }  
       [Display(Name = "Uploaded File")]  
       public String FileName { get; set; }  
       public byte[] FileContent { get; set; }  
  
  
   }  
Step 3 - Create Table and Stored Procedure
Now, create the stored procedure and the table to store the uploaded files in binary format and display back to the user's view. Use the script, given below, to create the table named FileDetails as-
CREATE TABLE [dbo].[FileDetails](  
    [Id] [int] IDENTITY(1,1) NOT NULL,  
    [FileName] [varchar](60) NULL,  
    [FileContent] [varbinary](max) NULL  
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
As mentioned in the preceding table script, we have created three columns Id, which is to identify the files unique key. FileName to store uploaded file name and FileContent to store the uploaded file contents in the binary format.
Create the stored procedure to insert the file details, using the script, given below-
Create Procedure [dbo].[AddFileDetails]  
(  
@FileName varchar(60),  
@FileContent varBinary(Max)  
)  
as  
begin  
Set NoCount on  
Insert into FileDetails values(@FileName,@FileContent)  
  
End  
To get the uploaded file details, use the code, given below-
CREATE Procedure [dbo].[GetFileDetails]  
(  
@Id int=null  
  
  
)  
as  
begin  
  
select Id,FileName,FileContent from FileDetails  
where Id=isnull(@Id,Id)  
End  
We have created the tables and stored procedures. I hope, you have created the same.
Step 4 - 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 in the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller . After modifying the code of Homecontroller class, the code will look like-
HomeController.cs
    using FileUploadDownLoadInMVC.Models;  
    using System;  
    using System.Collections.Generic;  
    using System.IO;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    using Dapper;  
    using System.Configuration;  
    using System.Data.SqlClient;  
    using System.Data;  
      
    namespace FileUploadDownLoadInMVC.Controllers  
    {  
        public class HomeController : Controller  
        {  
             
            #region Upload Download file  
            public ActionResult FileUpload()  
            {  
                return View();  
            }  
      
             
            [HttpPost]  
            public ActionResult FileUpload(HttpPostedFileBase files)  
            {  
      
             String FileExt=Path.GetExtension(files.FileName).ToUpper();  
      
                if (FileExt == ".PDF")  
                {  
                    Stream str = files.InputStream;  
                    BinaryReader Br = new BinaryReader(str);  
                    Byte[] FileDet = Br.ReadBytes((Int32)str.Length);  
      
                    FileDetailsModel Fd = new Models.FileDetailsModel();  
                    Fd.FileName = files.FileName;  
                    Fd.FileContent = FileDet;  
                    SaveFileDetails(Fd);  
                    return RedirectToAction("FileUpload");  
                }  
                else  
                {  
      
                    ViewBag.FileStatus = "Invalid file format.";  
                    return View();  
      
                }  
                 
            }  
             
            [HttpGet]  
            public FileResult DownLoadFile(int id)  
            {  
      
      
                List<FileDetailsModel> ObjFiles = GetFileList();  
      
                var FileById = (from FC in ObjFiles  
                                where FC.Id.Equals(id)  
                                select new { FC.FileName, FC.FileContent }).ToList().FirstOrDefault();  
      
                return File(FileById.FileContent, "application/pdf", FileById.FileName);  
      
            }  
            #endregion  
     
            #region View Uploaded files  
            [HttpGet]  
            public PartialViewResult FileDetails()  
            {  
                List<FileDetailsModel> DetList = GetFileList();  
      
                return PartialView("FileDetails", DetList);  
      
      
            }  
            private List<FileDetailsModel> GetFileList()  
            {  
                List<FileDetailsModel> DetList = new List<FileDetailsModel>();  
      
                DbConnection();  
                con.Open();  
                DetList = SqlMapper.Query<FileDetailsModel>(con, "GetFileDetails", commandType: CommandType.StoredProcedure).ToList();  
                con.Close();  
                return DetList;  
            }  
     
            #endregion  
     
            #region Database related operations  
            private void SaveFileDetails(FileDetailsModel objDet)  
            {  
      
                DynamicParameters Parm = new DynamicParameters();  
                Parm.Add("@FileName", objDet.FileName);  
                Parm.Add("@FileContent", objDet.FileContent);  
                DbConnection();  
                con.Open();  
                con.Execute("AddFileDetails", Parm, commandType: System.Data.CommandType.StoredProcedure);  
                con.Close();  
      
      
            }  
            #endregion  
     
            #region Database connection  
      
            private SqlConnection con;  
            private string constr;  
            private void DbConnection()  
            {  
                 constr =ConfigurationManager.ConnectionStrings["dbcon"].ToString();  
                 con = new SqlConnection(constr);  
      
            }  
            #endregion  
        }  
    }   
The preceding code snippet explained everything to upload and download PDF files from the database. I hope, you have followed the same.
Step 5 - Create strongly typed View
Right click on View folder of the created Application and create two strongly typed views; one is to upload the files by choosing EmpModel.cs class  and Partial View by choosing FileDetailsModel class to display the uploaded files. The code snippet of the view looks like-

FileUpload.cshtml
@model FileUploadDownLoadInMVC.Models.EmpModel  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
  
@using (Html.BeginForm("FileUpload", "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.FileStatus  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-8">  
                @Html.Action("FileDetails", "Home")  
  
            </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>  
FileDetails.cshtml
@model IEnumerable<FileUploadDownLoadInMVC.Models.FileDetailsModel>  
  
  
<table class="table table-bordered">  
    <tr>  
        <th class="col-md-4">  
            @Html.DisplayNameFor(model => model.FileName)  
        </th>  
          
        <th class="col-md-2"></th>  
    </tr>  
  
@foreach (var item in Model) {  
    <tr>  
        <td>  
            @Html.DisplayFor(modelItem => item.FileName)  
        </td>  
          
        <td>  
            @Html.ActionLink("Downlaod", "DownLoadFile", new { id=item.Id })   
             
        </td>  
    </tr>  
}  
  
</table> 
Now, we have done all the coding.

Step 6 - Run the Application
After running the Application, the UI of the Application will look like as follows-



Now select PDF file from your system and click Upload button. It will upload the file in the database and display back to the view is as follows-

Now, see the image, given below, of the table, which shows how the preceding uploaded file data is stored as-
From the preceding image, its clear that our uploaded file is stored into the database in the binary format. Now, click download button and it will show the following popup as-
Now, choose, whether to open the file or save the file according to your convenience. After opening the file, it will show the following contents, based on the uploaded file as-

I hope, from the preceding examples, you have learned, how to upload and download PDF files from the database In ASP.NET MVC, using FileResult.   
Note
  • Its important to define enctype = "multipart/form-data" in form action, else the value will be null in the controller.
  • Makes changes in web.config file connectionstring tag, based on your database location and configuration.
  • Since this is a demo, it might not be using the proper standards. Thus, improve it, depending on your skills.
Summary
I hope, this article is useful for all the readers. If you have any suggestions, please contact me.
Don't Forget To 

Downloading Files From DataBase in ASP.NET MVC

This articles explains the step by step how to download the files in ASP.NET MVC from database which is stored in a binary format , So lets learn step by step so beginners also can also understand .
Step 1 : View Binary formatted Uploaded Files

Step 2: Create an MVC Application.
Now, let us create a simple MVC application to download the uploaded  file as:
  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 3: Create Model Class
Now, let us create the model class file, named FileDetailsModel.cs, by right clicking on Models folder and define the following properties  as:
public class FileDetailsModel  
   {  
       public int Id { get; set; }  
       [Display(Name = "Uploaded File")]  
       public String FileName { get; set; }  
       public byte[] FileContent { get; set; }  
  
  
   }  
Step 4 : Create Stored Procedure
Now Create the stored procedure to view the uploaded files using following script as
CREATE Procedure [dbo].[GetFileDetails]  
(  
@Id int=null  
)  
as  
begin  
select Id,FileName,FileContent from FileDetails  
where Id=isnull(@Id,Id)  
End  
 I hope same you have created ;
Step 5 : 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 . After modifying the code of Homecontroller class, the code will look like:
HomeController.cs
    using System;  
    using System.Collections.Generic;  
    using System.IO;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    using Dapper;  
    using System.Configuration;  
    using System.Data.SqlClient;
    using FileUploadDownLoadInMVC.Models;  
    using System.Data;  
      
    namespace FileUploadDownLoadInMVC.Controllers  
    {  
        public class HomeController : Controller  
        {  
             
            #region Upload Download file  
            public ActionResult Index()  
            {  
                return View();  
            }  
                   
            [HttpGet]  
            public FileResult DownLoadFile(int id)  
            {  
      
      
                List<FileDetailsModel> ObjFiles = GetFileList();  
      
                var FileById = (from FC in ObjFiles  
                                where FC.Id.Equals(id)  
                                select new { FC.FileName, FC.FileContent }).ToList().FirstOrDefault();  
      
                return File(FileById.FileContent, "application/pdf", FileById.FileName);  
      
            }  
            #endregion  
     
            #region View Uploaded files  
            [HttpGet]  
            public PartialViewResult FileDetails()  
            {  
                List<FileDetailsModel> DetList = GetFileList();  
      
                return PartialView("FileDetails", DetList);  
      
      
            }  
            private List<FileDetailsModel> GetFileList()  
            {  
                List<FileDetailsModel> DetList = new List<FileDetailsModel>();  
      
                DbConnection();  
                con.Open();  
                DetList = SqlMapper.Query<FileDetailsModel>(con, "GetFileDetails", commandType: CommandType.StoredProcedure).ToList();  
                con.Close();  
                return DetList;  
            }  
     
            #endregion       
            #region Database connection  
      
            private SqlConnection con;  
            private string constr;  
            private void DbConnection()  
            {  
                 constr =ConfigurationManager.ConnectionStrings["dbcon"].ToString();  
                 con = new SqlConnection(constr);  
      
            }  
            #endregion  
        }  
    }   
The preceding code snippet explained everything to upload  PDF file into database , I hope you have followed the same .
 Step 6:  Create View
Right click on View folder of the created Application and create view named Index and Partial view FileDetails , The code snippet of the view's is look like as following .
Index.cshtml
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
  
@using (Html.BeginForm())  
{  
    @Html.AntiForgeryToken()    
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10 text-success">  
                @ViewBag.FileStatus  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-8">  
                @Html.Action("FileDetails", "Home")  
  
            </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>  
FileDetails.cshtml
@model IEnumerable<FileUploadDownLoadInMVC.Models.FileDetailsModel>  
<table class="table table-bordered">  
    <tr>  
        <th class="col-md-4">  
            @Html.DisplayNameFor(model => model.FileName)  
        </th>  
          
        <th class="col-md-2"></th>  
    </tr>  
  
@foreach (var item in Model) {  
    <tr>  
        <td>  
            @Html.DisplayFor(modelItem => item.FileName)  
        </td>  
          
        <td>  
            @Html.ActionLink("Downlaod", "DownLoadFile", new { id=item.Id })   
             
        </td>  
    </tr>  
}  
  
</table> 
Now, we have done all the coding.
Step 7 - Run the Application
After running the Application, the UI of the Application will look like as follows


Now click on download button , then it will shows the following popup


Choose to open or save the file , I have chosen to open the files , the contents of the files will be look like as follows


I hope, from the preceding examples, you have learned, how to download binary formatted PDF files from database.
Note
  • This article used dapper ORM to interact with the database. Thus, you need to install dapper ORM into the Application. If you don't know how to install dapper ORM in MVC, watch the video, using the link, given below-
  • Makes changes in web.config file connectionstring tag, based on your database location and configuration.
  • Since this is a demo, it might not be using the proper standards. Thus, improve it, depending on your skills.
Summary
I hope, this article is useful for all the readers. If you have any suggestions, please contact me.

Read related article
Don't Forget To 

Display Country List Without Database in ASP.NET MVC

When we need country name list to be use in an our application to serve the particular requirement we prefer to buy country database or web service or if cost issue then we prefer to create country name database manually 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 to capture all country names which are available in the world.
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:

www.CodeNirvana.in

Protected by Copyscape Online Copyright Protection
Copyright © Compile Mode