I'm trying to use the JQuery Form plugin (http://jquery.malsup.com/form/) to upload a file and a couple extra fields from my view, and I want the action method to return a Json result to the javascript callback.
Currently, the ActionMethod is called correctly (I can process the files and fields from the form) but when I return the Json result the browser tries to download it as a file (If I download the file and see its contents, it's the JSON content that I am returning.).
This is my form:
<form id="FormNewFile" action="@Url.Content("~/Home/AddFile")" method="post" enctype="multipart/form-data">
    <input type="hidden" name="eventId" value="25" />
    <input type="text" name="description" />
    <input type="file" name="fileName" />
    <input type="submit" value="Send!" />
</form>
This is my javascript:
  <script type="text/javascript">
     $(function () {
        $("#FormNewFile").ajaxForm({
           dataType:'json',
           success:processJson
     });
     });
     function processJson(a,b) {
        alert('success');
     }
  </script>
And this is my ActionMethod:
   [HttpPost]
   public ActionResult AddFile(long? eventId, string description)
   {
      int id = 5;
      return Json(new {id});
   }
The name of the file the browser tries to download is something like AddFilee87ce48e, with the last 8 characters being random hexadecimal characters.
And finally, the content of the file downloaded is:
{"id":5}
And the processJson function in javascript never gets called.
I googled a lot and the only thing that seems to work is returning the JSON result as a "Content" result from the action method, I think that's the approach I'm gonna take, but I still want to know why this isn't working?
Any ideas?
What I ended up doing was manually serializing the object I wanted to return as JSON, if I do this then the response won't have a header, therefore it will be handled by javascript instead of the browser. I used this helper method:
  public static ActionResult JsonPlain(object x)
  {
     var result = new ContentResult();
     result.Content = new JavaScriptSerializer().Serialize(x);
     return result;
  }
Hope this helps someone else
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With