1

Is it possible to automatically bind ASP.NET controllers model with an ajax request that submits data as FormData.

in my provided example I'm required to use HttpContext.Current.Request.Form["property_name"] to receive data because if I provide a model that is identical to the submitted form data, all values are equal to null;

or does ASP.NET model binding only work on JSON requests ?

Simple code bellow:

View:

@using (Html.BeginForm("Post", "Test", FormMethod.Post, new { @class="test-form"}))
{
    <input type="text" name="firstName"/>
    <input type="text" name="lastName"/>
    <button type="submit">Submit</button>
}

Scripts:

<script>
    $('.test-form').on('submit', function (e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            url: "@Url.Action("TestPost", "Test")",
            method: "POST",
            data: formData,
            processData: false,
            success: function(e){
            }
        });
    });
</script>

Controller:

    [HttpPost]
    public ActionResult TestPost()
    {
        var firstname = HttpContext.Current.Request.Form["firstName"];
        var lastName =  HttpContext.Current.Request.Form["lastName"];
        return PartialView("TestPost");
    }

Does Not Work Controller:

   public class User
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

   [HttpPost]
    public ActionResult TestPost(User model) //model values are null
    {

        return PartialView("TestPost");
    }
Stralos
  • 4,895
  • 4
  • 22
  • 40

1 Answers1

4

When you use a FormData object with ajax the data is sent as multipart/form-data and the content type header is set automatically for you with the correct boundary.
You can override the content type and set tit to whatever you want, which is what happens here.
You might be thinking well I didn't do it, well you good friend jQuery did it for you. It set the default content type for $.ajax for you (application/x-www-form-urlencoded) which pretty much craps up the request.
To stop this action i.e. to stop jQuery from setting a content type header you have to set the contentType parameter to false.

Musa
  • 96,336
  • 17
  • 118
  • 137