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