Thursday, 12 April 2018

Build a Single Page Application (SPA) with ASP.NETMVC

In traditional web applications, the client (browser) initiates the communication with the server by requesting a page. The server then processes the request and sends the HTML of the page to the client. 
In subsequent interactions with the page –e.g. the user navigates to a link or submits a form with data– a new request is sent to the server, and the flow starts again: the server processes the request and sends a new page to the browser in response to the new action requested by the client.
In Single-Page Applications (SPAs) the entire page is loaded in the browser after the initial request, but subsequent interactions take place through Ajax requests. This means that the browser has to update only the portion of the page that has changed; there is no need to reload the entire page. The SPA approach reduces the time taken by the application to respond to user actions, resulting in a more fluid experience.
The architecture of a SPA involves certain challenges that are not present in traditional web applications. However, emerging technologies like ASP.NET Web API, JavaScript frameworks like AngularJS and new styling features provided by CSS3 make it really easy to design and build SPAs.
So, let's learn step by step so beginners can also learn how to Create Single Page Application in ASPMVC.
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. create a New ASPMVC4 Application Named "MVCApplication35"
  2. Go to File->New->Project->ASP.NET MVC4 Web Application .Then Provide the Project Name as you wish.After clicking, the following window will appear :

  1. As shown in the preceding screenshot, click on the Basic template, then click OK. This will create an empty MVC web application.
Step 2: Add The Reference of  Helper Class

Now the next step is to add the reference of Dapper ORM into our created MVC Project. Here are the steps:
        Right click on Solution, find References Folder and Right click on it.
  1. Select Latest Version of System.web.Helper Class.
Step 3: Add The Model class

Go to Solution Explorer ->Models->Right Click on Models->Add ->Class->(Student.cs    
 public class Student
    {
        public int Procid { get; set; } 
       public int Id { getset; }
        public string Name { getset; }
       public int Age { getset; }
       public string Email { getset; }
        public string Address { getset; }
        public IList<Student> students { getset; }
    }
 Step 4: Add DataLayer  class

  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data.Entity;

namespace MvcApplication35.Models
{
    public class DataLayer:DbContext 
    {
        public DataLayer() : base("DataLayer")  { }
        public IEnumerable<Student>GetStudents(Student model)
        {
            SqlParameter []Para = new SqlParameter[]
            {
             new SqlParameter{ParameterName="@ProcId",Value=model.Procid},
            };
            string Query="Proc_Get_Students @ProcID";
            return this.Database.SqlQuery<Student>(Query, Para);
        }
    }
}


 Step 5: Add Connection string in Web Config.

  <add name="DataLayer" connectionString="Data Source=. ;Initial Catalog=test;User id=sa;Password=1" providerName="System.Data.SqlClient"/>

Step 6:  Add The Model class

Go to Solution Explorer ->Controllers->Right Click on Controllers->Add ->Controller->(HomeController.cs).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using MvcApplication35.Models;
namespace MvcApplication35.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            Student model = new Student(); model.Procid = 1;
            model.students = new DataLayer().GetStudents(model).ToList();
            return View(model);
        }
        [HttpPost]
        public ActionResult Index(Models.Student S)
        {
            return View("_Index", S);
        }
    }

}
Step 7:  Add View Right Clic Anywhere within action method Body and Add View(Index.cshtml)

@model MvcApplication35.Models.Student
@{
    ViewBag.Title = "Index";
}

<h2 style="text-align:center;font-family:Algerian;">Student Registration</h2>
<div class="container">
@using (Html.BeginForm())
{
    <div class="row">
    <table class="table table-responsive table-bordered">
        <tr>
            <th>@Html.LabelFor(y => y.Name)</th>
            <td>@Html.TextBoxFor(y=>y.Name,new { @class="form-control"})</td>
        </tr>
        <tr>
            <th>@Html.LabelFor(y=>y.Age)</th>
            <td>@Html.TextBoxFor(y=>y.Age,new { @class="form-control"})</td>
       </tr>
        <tr>
            <th>@Html.LabelFor(y=>y.Email)</th>
            <td>@Html.TextBoxFor(y=>y.Email,new { @class="form-control"})</td>
        </tr>
      <tr>
            <th>@Html.LabelFor(y=>y.Address)</th>
            <td>@Html.TextBoxFor(y=>y.Address,new { @class="form-control"})</td>
      </tr>
   </table>
    </div>
    <div class="row">
        <div class="col-xs-12 col-md-4">
            <input type="submit" value="Submit" class="btn btn-success" />
        </div>
    </div>
    <br />
    <div class="row">
    @if (Model != null && Model.students.Count > 0)
    {
        @Html.Partial("_Index", Model);
    }
    </div>
}
    </div>
<script></script>

Tuesday, 28 November 2017

ASPMVC , WebService , WCF Tutorial : Sending Emails In ASP.NET MVC From Controller Usin...

ASPMVC , WebService , WCF Tutorial : Sending Emails In ASP.NET MVC From Controller Usin...:  Sending Emails In ASP.NET MVC From Controller Using WebMail Helper Email communication is very important in today's modern applicati...

SENDING EMAILS IN ASP.NET MVC With Attachment

                         SENDING EMAILS IN ASP.NET MVC With Attachments 

In my previous article on Sending Emails In ASP.NET MVC with Web Mail , we have learned how to send emails from View using WebMail Class , Now in this article we will learn how to send emails in ASP.NET MVC from controller with Attachments. So let's learn step by step so beginners can also learn how to send emails in with Attachments  ASP.NET MVC from controller.

    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 MailModel.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.
    MailModel.cs class code snippet: 

    MailModel.cs

    1. public class MailModel {  
    2.     public string From {  
    3.         get;  
    4.         set;  
    5.     }  
    6.     public string To {  
    7.         get;  
    8.         set;  
    9.     }  
    10.     public string Subject {  
    11.         get;  
    12.         set;  
    13.     }  
    14.     public string Body {  
    15.         get;  
    16.         set;  
    17.     }  
    18. }  


    Step 2
    Create a New SendMailerController in the Controller folder let us add the MVC 5 controller as in the following screenshot:     

    The following is the code for the design of the new Controller.
    HomeController.cs
    1. using System;
      using System.Collections.Generic;
      using System.IO;
      using System.Linq;
      using System.Net;
      using System.Net.Mail;
      using System.Web;
      using System.Web.Mvc;

      namespace SendMailwithAttachment.Controllers
      {
          public class SendMailerController : Controller
          {
              public ActionResult Index()
              {
                  return View();
              }
              [HttpPost]
              public ActionResult Index(SendMailwithAttachment.Models.MailModel objModelMail, HttpPostedFileBasefileUploader)
              {
                  if (ModelState.IsValid)
                  {
                      string from = "Your Gmail Id"
                      using (MailMessage mail = new MailMessage(from, objModelMail.To))
                      {
                          mail.Subject = objModelMail.Subject;
                          mail.Body = objModelMail.Body;
                          if (fileUploader != null)
                          {
                              string fileName = Path.GetFileName(fileUploader.FileName);
                              mail.Attachments.Add(new Attachment(fileUploader.InputStream, fileName));
                          }
                          mail.IsBodyHtml = false;
                          SmtpClient smtp = new SmtpClient();
                          smtp.Host = "smtp.gmail.com";
                          smtp.EnableSsl = true;
                          NetworkCredential networkCredential = new NetworkCredential(from, "Your Gmail Password");
                          smtp.UseDefaultCredentials = true;
                          smtp.Credentials = networkCredential;
                          smtp.Port = 587;
                          smtp.Send(mail);
                          ViewBag.Message = "Sent";
                          return View("Index", objModelMail);
                      }
                  }
                  else
                  {
                      return View();
                  }
              }
          }
      }

       Step 4 : 

      Create  view named Index.
      Right click on View folder of created application and choose add view . As shown in the following image,



      Now open the Index.cshtml view , and Write the following Code

        Index.cshtml 

    • @model SendMailwithAttachment.Models.MailModel
      @{
          ViewBag.Title = "Index";
      }
      <script src="~/Scripts/jquery-1.7.1.min.js"></script>
      <script>
          $(document).ready(function () {
              if ('@ViewBag.Message' == 'Sent') {
                  alert('Mail has been sent successfully');
              }
          });
      </script>
      <h2>Index</h2>
      <fieldset>
          <legend>Send Email
          </legend> 
          @using (@Html.BeginForm("Index""SendMailer"FormMethod.Post, new { @id = "form1", @enctype ="multipart/form-data" }))
          {
              @Html.ValidationSummary()
              <input type="submit" value="Send" />
          
              <table>
                  <tr>
                      <td>To:
                      </td>
                          @Html.TextBoxFor(m => m.To)
                      </td>
                  </tr>
                  <tr>
                      <td>Subject:
                      </td>
                      <td>
                          @Html.TextBoxFor(m => m.Subject)
                      </td>
                  </tr>
                  <tr>
                      <td>Attachment
                      </td>
                      <td>
                          <input type="file" name="fileUploader" />
                      </td>
                  </tr>
                  <tr>
                      <td>Body:
                      </td>
                      <td>
                          @Html.TextAreaFor(m => m.Body)
                      </td>
                  </tr> 
              </table>    
          }
      </fieldset>


    • Now we have done all coding to send emails using WebMail class.

      Step 5 : Now run the application.