1

I have a form that that is not being passed to my controller. It is hitting the controller method, but fails in passing any parameters, 'jsonString' is always NULL.

** Note: I have also tried using @razor w. model binding but was having the same issues.

Form:

 <form id="CarreersForm">
            <div class="form-group">
                @Html.Label("Name")<br />
                @Html.TextBoxFor(m => m.name)  
            </div>
            <div class="form-group">
                @Html.Label("Phone")<br />
                @Html.TextBoxFor(m => m.phone)
                @Html.ValidationMessage("Phone", new { @class = "text-danger" })
            </div>
            <div class="form-group">
                @Html.Label("Email")<br />
                @Html.TextBoxFor(m => m.email) 
            </div>   
            <div class="form-group">
                <input type="file" id="filepath" name="filepath" value="Upload Resume" class="btn btn-default" />
            <input type="submit" name="submit" id="submit" value="submit" />
        </form>

JS/AJAX:

<script>
    $(function () {
        $("#submit").click(function (e) {
            e.preventDefault();
            var formData = {
                "name": $("#CarreersForm  #name").val(),
                "phone": $("#CarreersForm  #phone").val(),
                "email": $("#CarreersForm  #email").val(),
                "filepath": $("#CarreersForm  #filepath").val(),
            };
            var jsonString = JSON.stringify(formData);
            console.log(jsonString);
            $.ajax({
                type: 'POST',
                data: jsonString,
                url: "@Url.Action("CarreersForm")",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                cache: false,
                success: function (response) {
                    if (response == 'True') {
                        alert("The form was successfully submitted.");
                        $("#contactUs form input").val("");
                    }
                    if (response == 'False') {
                        alert("There was an error submitting the form. Fill in all of the form fields with no errors.");
                    }
                },
                error: function (response) {
                    alert("There was an error submitting the form. Fill in all of the form fields with no errors.");
                }
            });
        });
    });
</script>

Controller:

//Current Method
[HttpPost]
public bool CarreersForm(string jsonString)   
{
    return false;
}

Copy of HTTP POST

NEW REQUEST
POST http://localhost:51721/Transportation/CarreersForm

REQUEST HEADERS:
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost:51721/Transportation/Careers
Content-Length: 95
Cache-Control: no-cache

REQUEST BODY
{"name":"Mark","phone":"123456789","email":"email@emailaccount.com","filepath":"logo_main.png"}

CareersModel:

public class CareersModel
    {

        [Required]
        public string name { get; set; }

        public string job { get; set; }

        [Required]
        [EmailAddress]
        public string email { get; set; }

        [Phone]
        public string phone { get; set; }


        [Required]
        public HttpPostedFileBase filepath { get; set; }


    }

I have also tried passing the model directly:

  [HttpPost]
        public bool CarreersForm(ContactForm model)   
        {

             if (!ModelState.IsValid){
                    return false;
              }
         return true;
     }
Mark
  • 4,773
  • 8
  • 53
  • 91
  • ASP.NET MVC does the model binding, so controller is supposed to receive several parameters, like `string name, string phone, ...`, or a class with named properties for these. If for some reason you need the raw json string that came in request body, check out this [answer](http://stackoverflow.com/questions/13041808/mvc-controller-get-json-object-from-http-body) – Andrei Mar 20 '15 at 12:33
  • Yes, I have tried this too, but like I said I was having the same issue, nothing was being passed. – Mark Mar 20 '15 at 12:39
  • Can you post your controller for this second attempt? – Andrei Mar 20 '15 at 12:41
  • What about `data: $("form").serialize()`? Can you post your `ContactForm` model? – Mathew Thompson Mar 20 '15 at 12:52
  • @mattytommo, I have also tried that, I see the value in the HTTP POST, but nothing is being passed to my controller. See edit for model – Mark Mar 20 '15 at 12:54
  • Have you tried creating the post manually and firing it, for example with PostMan plugin? – nik0lai Mar 20 '15 at 14:58
  • have you tried removing your data annotation validation (such as [EmailAddress], [Phone], etc.) to see if maybe a field is not formatted according to the specifications? – Daniel Sanchez Mar 20 '15 at 15:08
  • 1
    Also, as matty mentioned, you posted the CareersModel, but not the ContactForm model, which you're expecting in your POST. – Daniel Sanchez Mar 20 '15 at 15:11

3 Answers3

1

I'm fairly certain that this is because you haven't set the correct encoding type on your form. Change it to the following to allow uploading files, this'll allow successful submission of your model.

<form id="CarreersForm" enctype="multipart/form-data">

Also: You won't be able to upload your documents using a jQuery AJAX request like that. It'd have to be either a standard post request, or using a plugin that allows ajaxified file uploads.

Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • Thanks for the heads up about not being to upload file like this. But even when I comment the file out, I am unable to pass anything to the controller. – Mark Mar 20 '15 at 13:09
  • That's very strange, everything else seems fine. When you're debugging in the controller, what's inside `Request.Form`? – Mathew Thompson Mar 20 '15 at 13:10
  • Nothing, at the moment, nothing at all is being passed into the method. The model is empty. – Mark Mar 20 '15 at 13:16
  • @Mark Ah of course you're sending it via AJAX now, my bad. The only other thing I would suggest is removing the `contentType` to see if that made a difference. – Mathew Thompson Mar 20 '15 at 13:29
  • 1
    @Mark Actually, as @Daniel Sanchez says, you're posting the `CareersModel`, but expecting the `ContactFormModel` – Mathew Thompson Mar 20 '15 at 15:13
0
       var formData = new FormData($("#CarreersForm")[0]);

use in ajax to data pass "data: jsonString,"

0

e.preventDefault() is the problem. It should come last with respect to your code arrangement as it only prevents the default action of the form from following the link provided in the form action attribute.

e.preventDefault() can prevent your form from passing the form parameters because it returns false and the rest of your commands have not been executed.

Also remember that e.preventDefault() method is supposed to be called on the form object itself, wherein you called it on the click event handler of the submit button.

Also setting request headers can prevent your Ajax from passing the form parameters to the PHP processing file.

Martin54
  • 1,349
  • 2
  • 13
  • 34