Skip to content
This repository has been archived by the owner on Feb 20, 2021. It is now read-only.

Latest commit

 

History

History

ASP.NET MVC5 - SendEmail and save it with EF6

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

ASP.NET MVC5 - SendEmail and save it with EF6

Requires

  • Visual Studio 2015

License

  • MIT

Technologies

  • C#
  • ASP.NET
  • ASP.NET MVC
  • ASP.NET MVC 5
  • MVC Scaffolding

Topics

  • C#
  • ASP.NET
  • ASP.NET MVC
  • ASP.NET MVC 5

Updated

  • 11/07/2015

Description

Using MVC, Entity Framework, and ASP.NET Scaffolding, you can create a web application that provides an interface to an existing database table. This demo shows you how to automatically generate code that enables users to display, edit, create, and delete data that resides on the database. The generated code corresponds to the columns in the database table.

This demo focuses on using ASP.NET Scaffolding to generate the controllers and views.

 

STEP1 -  Create new project on Visual Studio 2015

Open Visual Studio

Create new ASP.NET Web Application Project

Give a name to the project (in this case I call him MVC5)

Select Template MVC

 

 

STEP2 -  Create class Email

Add new class to the project (this class represents a table, and the properties the colums of that table)

Give a name to that class (in my sample I call him EmailModel)

On the class create the following code:

 

C#
Editar Script|Remove
csharp
using System; 
using System.Collections.Genericusing System.Data.Entityusing System.Dynamicusing System.Linqusing System.Web; 
 
namespace MVC5.Models 
{ 
    public class Email 
    { 
        public int ID { getset; } 
        public string To { getset; } 
        public string Subject { getset; } 
        public string Message { getset; } 
    } 
 
    public class EmailDBContext : DbContext 
    { 
        public DbSet<Email> Emails { getset; } 
    } 
}
Put the class inside the Models folders, just to organize your code.

 

STEP3 -  Create controller with views using Entity Framework

Add new Scaffolded to the project (new item existent on MVC5)

 

 

 

 Choose option MVC5 Controller with views using Entity Framework

 

Click Add

If you receive an error, it may be because you did not build the project in the previous section. If so, try building the project, and then add the scaffolded item again.

After the code generation process is complete, you will see a new controller and views in your project.

 

STEP4 - Controller and Views Generation

The Controller was automatically created with CRUD operations

C#
Editar Script|Remove
csharp
using System; 
using System.Collections.Genericusing System.Datausing System.Data.Entityusing System.Linqusing System.Threading.Tasksusing System.Netusing System.Webusing System.Web.Mvcusing MVC5.Models; 
 
namespace MVC5.Controllers 
{ 
    publicclass EmailsController : Controller 
    { 
        private EmailDBContext db = new EmailDBContext(); 
 
        // GET: Emailspublic async Task<ActionResult> Index() 
        { 
            return View(await db.Emails.ToListAsync()); 
        } 
 
        // GET: Emails/Details/5public async Task<ActionResult> Details(int? id) 
        { 
            if (id == null) 
            { 
                returnnew HttpStatusCodeResult(HttpStatusCode.BadRequest); 
            } 
            Email email = await db.Emails.FindAsync(id); 
            if (email == null) 
            { 
                return HttpNotFound(); 
            } 
            return View(email); 
        } 
 
        // GET: Emails/Createpublic ActionResult Create() 
        { 
            return View(); 
        } 
 
        // POST: Emails/Create// To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. 
        [HttpPost] 
        [ValidateAntiForgeryToken] 
        public async Task<ActionResult> Create([Bind(Include = "ID,To,Subject,Message")] Email email) 
        { 
            if (ModelState.IsValid) 
            { 
                db.Emails.Add(email); 
                await db.SaveChangesAsync(); 
                Services.EmailService emailService = new Services.EmailService(); 
                await emailService.SendEmailAsync(email.To, email.Message, email.Subject); 
                return RedirectToAction("Index"); 
            } 
 
            return View(email); 
        } 
 
        // GET: Emails/Edit/5public async Task<ActionResult> Edit(int? id) 
        { 
            if (id == null) 
            { 
                returnnew HttpStatusCodeResult(HttpStatusCode.BadRequest); 
            } 
            Email email = await db.Emails.FindAsync(id); 
            if (email == null) 
            { 
                return HttpNotFound(); 
            } 
            return View(email); 
        } 
 
        // POST: Emails/Edit/5// To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. 
        [HttpPost] 
        [ValidateAntiForgeryToken] 
        public async Task<ActionResult> Edit([Bind(Include = "ID,To,Subject,Message")] Email email) 
        { 
            if (ModelState.IsValid) 
            { 
                db.Entry(email).State = EntityState.Modified; 
                await db.SaveChangesAsync(); 
                return RedirectToAction("Index"); 
            } 
            return View(email); 
        } 
 
        // GET: Emails/Delete/5public async Task<ActionResult> Delete(int? id) 
        { 
            if (id == null) 
            { 
                returnnew HttpStatusCodeResult(HttpStatusCode.BadRequest); 
            } 
            Email email = await db.Emails.FindAsync(id); 
            if (email == null) 
            { 
                return HttpNotFound(); 
            } 
            return View(email); 
        } 
 
        // POST: Emails/Delete/5 
        [HttpPost, ActionName("Delete")] 
        [ValidateAntiForgeryToken] 
        public async Task<ActionResult> DeleteConfirmed(int id) 
        { 
            Email email = await db.Emails.FindAsync(id); 
            db.Emails.Remove(email); 
            await db.SaveChangesAsync(); 
            return RedirectToAction("Index"); 
        } 
 
        protectedoverridevoid Dispose(bool disposing) 
        { 
            if (disposing) 
            { 
                db.Dispose(); 
            } 
            base.Dispose(disposing); 
        } 
    } 
} 

STEP5 - Create Email Service

 

C#
Editar Script|Remove
csharp
using System; 
using System.Collections.Genericusing System.Linqusing System.Netusing System.Net.Mailusing System.Textusing System.Threading.Tasks; 
 
namespace Services 
{ 
    public class EmailService 
    { 
        public async Task<bool> SendEmailAsync(string emailTo, string mailbody, string subject) 
        { 
            var from = new MailAddress("abc@abc.com"); 
            var to = new MailAddress(emailTo); 
 
            var useDefaultCredentials = true; 
            var enableSsl = false; 
            var replyto = ""// set here your email; 
            var userName = string.Empty; 
            var password = string.Empty; 
            var port = 25; 
            var host = "localhost"; 
 
            userName = "abc"// setup here the username; 
            password = "abc"// setup here the password; 
            bool.TryParse("true"out useDefaultCredentials); //setup here if it uses defaault credentials 
            bool.TryParse("true"out enableSsl); //setup here if it uses ssl 
            int.TryParse("25"out port); //setup here the port 
            host = "www.google.com"//setup here the host 
 
            using (var mail = new MailMessage(from, to)) 
            { 
                mail.Subject = subject; 
                mail.Body = mailbody; 
                mail.IsBodyHtml = true; 
 
                mail.ReplyToList.Add(new MailAddress(replyto, "My Email")); 
                mail.ReplyToList.Add(from); 
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Delay | 
                                                   DeliveryNotificationOptions.OnFailure | 
                                                   DeliveryNotificationOptions.OnSuccess; 
 
                using (var client = new SmtpClient()) 
                { 
                    client.Host = host; 
                    client.EnableSsl = enableSsl; 
                    client.Port = port; 
                    client.UseDefaultCredentials = useDefaultCredentials; 
 
                    if (!client.UseDefaultCredentials && !string.IsNullOrEmpty(userName) && 
                        !string.IsNullOrEmpty(password)) 
                    { 
                        client.Credentials = new NetworkCredential(userName, password); 
                    } 
 
                    await client.SendMailAsync(mail); 
                } 
            } 
 
            return true; 
        } 
    } 
} 

MVC5 Resources

Some good online resources about MVC5:

ASP.NET MVC5 : The official Microsoft .NET WebSite
http://www.asp.net/mvc/tutorials/mvc-5

 

For more examples, follow my blog at

http://joaoeduardosousa.wordpress.com/

 

Check my other source code:

http://code.msdn.microsoft.com/MVC4-ENTITY-FRAMEWORK-10-e15ef983

http://code.msdn.microsoft.com/ASPNET-MVC-5-Bootstrap-30-622be454

http://code.msdn.microsoft.com/MVC5-Authentication-App-b5200efd

http://code.msdn.microsoft.com/ASPNET-WebAPI-2-Stream-7d96cb70

http://code.msdn.microsoft.com/ASPNET-WebAPI-Basic-Redis-ade42ca7

http://code.msdn.microsoft.com/ASPNET-WebApi-Use-Redis-as-a0d942a3

http://code.msdn.microsoft.com/ASPNET-MVC-connect-with-1f40770f

http://code.msdn.microsoft.com/ASPNET-WebAPI-Enable-Cors-666b88eb

http://code.msdn.microsoft.com/ASPNET-WebAPI-Entity-2f8797a1