0

I have an Asp.net core application in which I have a form. When I click on the submit button I am using jquery ajax post to submit the form. I am facing 2 problems here,

  1. When I press the submit button, the client side validations are not happening and the form is being submitted.
  2. I have a Break point in the SendEmail Method, and for some reason the FormData binds all null values to the object. Please help.

Here is my form

<form name="ajax-form" id="formPostComment" enctype="multipart/form-data" method="post">
                            <div class="col-sm-6 contact-form-item wow zoomIn">
                                <input name="name" id="name" type="text" placeholder="Your Name: *" required/>
                                <span class="error" id="err-name">please enter name</span>
                            </div>
                            <div class="col-sm-6 contact-form-item wow zoomIn">
                                <input name="email" id="email" type="text" placeholder="E-Mail: *" required/>
                                <span class="error" id="err-email">please enter e-mail</span>
                                <span class="error" id="err-emailvld">e-mail is not a valid format</span>
                            </div>
                            <div class="col-sm-6 contact-form-item wow zoomIn">
                                <label for="myfiles">Select file (If Any):</label>
                                <input name="attachment" id="attachment" type="file" />
                            </div>
                            <div class="col-sm-12 contact-form-item wow zoomIn">
                                <textarea name="message" id="message" placeholder="Your Message" required></textarea>
                            </div>
                            <div class="col-sm-12 contact-form-item">
                                <input class="send_message btn btn-main btn-theme wow fadeInUp" type="submit" id="submit" name="submit" data-lang="en" onclick="SendEmail();"></input>
                            </div>
                            <div class="clear"></div>
                            <div class="error text-align-center" id="err-form">There was a problem validating the form please check!</div>
                            <div class="error text-align-center" id="err-timedout">The connection to the server timed out!</div>
                            <div class="error" id="err-state"></div>
                        </form>

<script>
 function SendEmail() {
            var formData = new FormData();
            formData.append("Name", $("#name").val());
            formData.append("Email", $("#email").val());
            formData.append("Attachment", $("#attachment")[0]);
            formData.append("Message", $("#message").val());
            alert($("#name").val());
            $.ajax({
                type: 'POST',
                url: "/Home/SendEmail",
                data: formData,
                processData: false,
                contentType: false,
                cache: false,
                success: function (response) {
                    alert("Done");
                    $('#formPostComment')[0].reset();
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
            //}).done(function (data) {
            //    console.log(data);
            //    $("#ajaxwaiting").hide();
            //    $("#ajaxsuccess").show();
            //});
            event.preventDefault();
        }
</script>

Here is my Controller action method.

 [HttpPost]
        public IActionResult SendEmail([Bind("Name,Email,Attachment,Message")] SingleEmailMessage message)
        {
            return Json(new { data = "DONE" });
        }

The SingleEmailMessage class is as follows,

public class SingleEmailMessage
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public IFormFile Attachment { get; set; }
        public string Message { get; set; }
    }
nikhil
  • 1,578
  • 3
  • 23
  • 52

1 Answers1

0

you might be sending two POSTs here... don't use onclick on the submit... instead use onsubmit on the form tag... ex: <form ... onsubmit="SendEmail(); return false;"> Don't forget the "return false;" bit that replaces your event.preventDefault() call. It's also easier to pass the form's ID into your function... so

    SendEmail("formPostComment")... then function SendEmail(id) {
...
    thisForm = document.getElementById(id);
        var formData = new FormData(thisForm);

On controller side get the file by using:

if (Request.Form.Files.Count > 0)
            {
                IFormFile file = Request.Form.Files[0];
            }

Not sure that the file is going to bind to your model.... get it from the raw request.

The full JS function I use is this (just for reference):

//for uploads
function PostFileFormID(id, buttonid, destURL) {
   
    $('#' + buttonid).attr('value', "Uploading...");
    thisForm = document.getElementById(id);
    var formData = new FormData(thisForm);

    jQuery.ajax({
        type: 'POST',
        url: destURL,
        data: formData,
        processData: false,
        contentType: false,
        success: function (data) {
           params = convertJsonToParams(data);
           url = "?" + params;    
           setLocation(url);
        },
        error: function (jqXHR, textStatus, error) {
            DisplaySuperError(jqXHR, textStatus, error);


        }
    });
}
pcalkins
  • 1,188
  • 13
  • 20
  • Sure thank you let me try. – nikhil Oct 21 '22 at 20:03
  • btw, when binding to a model it's easier to use HTML helpers like @Html.EditorFor(model => model.your_initializedSendEmailMessage.Name)... etc.. Then you don't need any arguments in your controller's SendEmail() method. Just bind the initialized SendEmailMessage class. It's possible the file will bind too... but I've never used HTML helper for file uploads... maybe see here: https://stackoverflow.com/questions/304617/html-helper-for-input-type-file – pcalkins Oct 21 '22 at 20:11
  • 1
    Thank you so much the onsubmit fixed my first issue. For the second issue, I can't understand how much dumb I am. Honestly the issue was the parameter name for the ActionMethod. When I hover the mouse, it says ' Property on SingleEmailMessage has the same name as parameter message. This can lead to incorrect Model Binding'. I changed the parameter name and it works. – nikhil Oct 21 '22 at 20:20
  • 1
    the "message" param was the problem? It's actually not the same, but ASP.NET does funny things with case I guess. I think it ignores case on query vars. Interesting that the file did bind, though... I'll be doing that in the future! – pcalkins Oct 21 '22 at 21:30