locked
how to convert html helper to ajax RRS feed

  • Question

  • User-1634604574 posted

    i have this code which is html helper submit button and controller is action result i want when i click on button submit by ajax run 

    jsonresult from controller instead action result

    index view

    <style>
        #viewContent h3 {
            margin: 10px 0;
        }
    
        #viewContent h3 {
            color: #ee14f7;
            text-align: left;
        }
    
        #viewContent .emailDiv label {
            display: block;
            margin: 0;
            text-transform: capitalize;
        }
    
        #viewContent table tr td > span {
            display: block;
            color: burlywood;
        }
    
        #viewContent .emailDiv > form > div > div {
            padding-top: 25px;
        }
    
        #viewContent table {
            width: 100%;
        }
    </style>
    <script src="~/Content/Component/ckeditor/ckeditor.js" type="text/javascript" language="javascript"></script>
    
    @model SendEmail.Models.SendEmail
    @{
        var title = "Send HTML Email with Attachments in ASP NET MVC using C#";
        ViewBag.Title = title;
        <h1>@title</h1>
    }
    <h2>
        <a href="http://www.yogihosting.com/asp-net-send-email/">Read the tutorial on YogiHosting » </a>
        @using (Html.BeginForm("Reset", "SendEmail"))
        {
            <button id="reset">Reset »</button>
        }
    </h2>
    <div id="viewContent">
        <h3>@ViewBag.Result</h3>
        <div class="emailDiv">
            @using (Html.BeginForm("Index", "SendEmail", FormMethod.Post, new { enctype = "multipart/form-data" }))
                {
                <table>
                    <tr>
                        <td>
                            @Html.LabelFor(model => model.to)
                            @Html.EditorFor(model => model.to)
                            @Html.ValidationMessageFor(model => model.to)
                        </td>
    
                     
                        <td>
                            @Html.LabelFor(model => model.subject)
                            @Html.EditorFor(model => model.subject)
                            @Html.ValidationMessageFor(model => model.subject)
                        </td>
                    </tr>
                    <tr>
                        <td>
                            @Html.LabelFor(model => model.file)
                            @Html.TextBoxFor(m => m.file, new { type = "file", multiple = "multiple" })
                            @Html.ValidationMessageFor(model => model.file)
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            @Html.LabelFor(model => model.body)
                            @Html.TextAreaFor(model => model.body)
                            <script type="text/javascript" language="javascript">
                                CKEDITOR.replace(@Html.IdFor(model => model.body));
                            </script>
                            @Html.ValidationMessageFor(model => model.body)
                        </td>
                    </tr>
                    <tr><td><button id="submitButton" type="submit">Submit</button></td></tr>
                </table>
            }
        </div>
    </div>

    sendEmail.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
    
    namespace SendEmail.Models
    {
        public class SendEmail
        {
            [Required]
            [RegularExpression(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$", ErrorMessage = "Invalid email")]
            public string to { get; set; }
    
         
    
            [Required]
            public string subject { get; set; }
    
            [Required]
            public string body { get; set; }
    
            public HttpPostedFileBase[] file { get; set; }
        }
    }

    SendEmail.controller

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Net.Mail;
    using System.IO;
    
    namespace SendEmail.Controllers
    {
        public class SendEmailController : Controller
        {
            // GET: SendEmail
            public ActionResult Index()
            {
                return View();
            }
    
            [HttpPost]
            [ValidateInput(false)]
            public ActionResult Index(SendEmail.Models.SendEmail sendEmail)
            {
                string path = "~/Content/Upload/" + Guid.NewGuid().ToString() + "/";
                if (ModelState.IsValid)
                {
                    MailMessage mailMessage = new MailMessage();
                    mailMessage.From = new MailAddress("zhyanadil.it@gmail.com");
                    mailMessage.To.Add(new MailAddress(sendEmail.to));
                    mailMessage.CC.Add(new MailAddress("zhyanadil.it@gmail.com"));
                    mailMessage.Bcc.Add(new MailAddress("zhyanadil.it@gmail.com"));
    
                    mailMessage.Subject = sendEmail.subject;
                    mailMessage.IsBodyHtml = true;
                    mailMessage.Body = sendEmail.body;
    
                    if (sendEmail.file[0] != null)
                    {
                        Directory.CreateDirectory(Server.MapPath(path));
                        foreach (HttpPostedFileBase file in sendEmail.file)
                        {
                            string filePath = Server.MapPath(path + file.FileName);
                            file.SaveAs(filePath);
    
                            mailMessage.Attachments.Add(new Attachment(Server.MapPath(path + file.FileName)));
                        }
                    }
    
                    SmtpClient client = new SmtpClient();
                    client.Credentials = new System.Net.NetworkCredential("zhyanadil.it@gmail.com", "***");
                    client.Host = "smtp.gmail.com";
                    client.Port = 587;
                    client.EnableSsl = true;
    
                    try
                    {
                        client.Send(mailMessage);
                        ViewBag.Result = "Mail Sent";
                    }
                    catch (Exception ex)
                    {
                        ViewBag.Result = ex.Message;
                    }
                }
    
                return View();
            }
    
            [HttpPost]
            public ActionResult Reset()
            {
                return RedirectToAction("Index");
            }
        }
    }

    Friday, July 31, 2020 9:20 AM

All replies

  • User475983607 posted

    There is no AJAX code anywhere in your code snippets.

    Friday, July 31, 2020 10:38 AM
  • User-1634604574 posted

    i mean my code calling method controller by this code

            @using (Html.BeginForm("Index", "SendEmail", FormMethod.Post, new { enctype = "multipart/form-data" }))

    but i want instead that code write ajax code to execute method controller SendEmail

    and convert SenEmail method from actionresult to jsonresult

    now are you understand what i mean?

    Friday, July 31, 2020 11:21 AM
  • User475983607 posted

    i mean my code calling method controller by this code

            @using (Html.BeginForm("Index", "SendEmail", FormMethod.Post, new { enctype = "multipart/form-data" }))
    
    but i want instead that code write ajax code to execute method controller SendEmail

    and convert SenEmail method from actionresult to jsonresult

    now are you understand what i mean?

    Are you asking the community to find tutorials for you that illustrates how to use the Ajax.BeginForm?  Below are the first three found in with a basic Google search.

    https://www.c-sharpcorner.com/article/asp-net-mvc-5-ajax-beginform-ajaxoptions-onsuccess-onfailure/

    https://stackoverflow.com/questions/17095443/how-to-use-simple-ajax-beginform-in-asp-net-mvc-4

    https://www.aspsnippets.com/Articles/ASPNet-MVC-AjaxBeginForm-Tutorial-with-example.aspx

    Friday, July 31, 2020 11:34 AM
  • User-1634604574 posted

    no no no you are always not understand on my post thank you let another one answer my thread

    Friday, July 31, 2020 2:33 PM
  • User475983607 posted

    zhyanadil.it@gmail.com

    no no no you are always not understand on my post thank you let another one answer my thread

    It's sad really.  Just a few minor tweaks and your code would be AJAX ready.  It's baffling why you did not try...

    1) Add the unobtrusive AJAX NuGet Package.

    Install-Package Microsoft.jQuery.Unobtrusive.Ajax -Version 3.2.6

    Next update the markup.

    @model MvcBasic.Models.SendEmail
    @{
        var title = "Send HTML Email with Attachments in ASP NET MVC using C#";
        ViewBag.Title = title;
        <h1>@title</h1>
    }
    <h2>
        <a href="http://www.yogihosting.com/asp-net-send-email/">Read the tutorial on YogiHosting » </a>
        @using (Html.BeginForm("Reset", "SendEmail"))
        {
            <button id="reset">Reset »</button>
        }
    </h2>
    <div id="viewContent">
        <div id="resultTarget"></div>
        <div class="emailDiv">
            @using (Ajax.BeginForm("Index", "SendEmail", null,
                new AjaxOptions { HttpMethod = "POST",
                    OnSuccess = "OnSuccess",
                    OnFailure = "OnFailure",
                    UpdateTargetId = "resultTarget"
                }))
            {
                <table>
                    <tr>
                        <td>
                            @Html.LabelFor(model => model.to)
                            @Html.EditorFor(model => model.to)
                            @Html.ValidationMessageFor(model => model.to)
                        </td>
    
    
                        <td>
                            @Html.LabelFor(model => model.subject)
                            @Html.EditorFor(model => model.subject)
                            @Html.ValidationMessageFor(model => model.subject)
                        </td>
                    </tr>
                    <tr>
                        <td>
                            @Html.LabelFor(model => model.file)
                            @Html.TextBoxFor(m => m.file, new { type = "file", multiple = "multiple" })
                            @Html.ValidationMessageFor(model => model.file)
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            @Html.LabelFor(model => model.body)
                            @Html.TextAreaFor(model => model.body)
                            <script type="text/javascript" language="javascript">
                                CKEDITOR.replace(@Html.IdFor(model => model.body));
                            </script>
                            @Html.ValidationMessageFor(model => model.body)
                        </td>
                    </tr>
                    <tr><td><button id="submitButton" type="submit">Submit</button></td></tr>
                </table>
            }
        </div>
    </div>
    @section scripts
    {
        <script>
            function OnSuccess(data) {
                console.log('HTTP Status Code: ' + data.param1 + "  " + data.param2);
            }
            function OnFailure(data) {
                console.log('HTTP Status Code: ' + data.param1 + '  Error Message: ' + data.param2);
            } 
        </script>
    }

    Update the controller to return a partial

                    try
                    {
                        client.Send(mailMessage);
                        ViewBag.Result = "Mail Sent";
                    }
                    catch (Exception ex)
                    {
                        ViewBag.Result = ex.Message;
                        return PartialView("_EmailResults");
                    }
                }
                ViewBag.Result = "Success";
                return PartialView("_EmailResults");

    Add the _EmailResults partial

    <div>
        @ViewBag.Result
    </div>

    If you are trying to built a jQuery/AJAX solution then, IMHO, that is far too much free coding and design work.  This is a support forum not free coding.   You should make a good faith attempt to solve "your" problem.  If you need help share your code.  Explain how you expect the code to function and what actually happens.

    Friday, July 31, 2020 4:59 PM