Home > Software engineering >  FormData not binding values to controller
FormData not binding values to controller

Time:10-22

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 >
                                <input name="name" id="name" type="text" placeholder="Your Name: *" required/>
                                <span  id="err-name">please enter name</span>
                            </div>
                            <div >
                                <input name="email" id="email" type="text" placeholder="E-Mail: *" required/>
                                <span  id="err-email">please enter e-mail</span>
                                <span  id="err-emailvld">e-mail is not a valid format</span>
                            </div>
                            <div >
                                <label for="myfiles">Select file (If Any):</label>
                                <input name="attachment" id="attachment" type="file" />
                            </div>
                            <div >
                                <textarea name="message" id="message" placeholder="Your Message" required></textarea>
                            </div>
                            <div >
                                <input  type="submit" id="submit" name="submit" data-lang="en" onclick="SendEmail();"></input>
                            </div>
                            <div ></div>
                            <div  id="err-form">There was a problem validating the form please check!</div>
                            <div  id="err-timedout">The connection to the server timed out!</div>
                            <div  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; }
    }

CodePudding user response:

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);


        }
    });
}
  • Related