In MVC how to call .ashx handler file through jque

2019-09-01 01:52发布

In mvc i need to call .ashx handler file through jquery.

i tried the bleow code

 $("#btnUpload").click(function (evt) {

    var fileUpload = $("#file1").get(0);
    var files = fileUpload.files;

    var data = new FormData();
    for (var i = 0; i < files.length; i++) {
        data.append(files[i].name, files[i]);
    }

    var options = {};
    options.url = "FileUploadHandler.ashx";
    options.type = "POST";
    options.data = data;
    options.contentType = false;
    options.processData = false;
    options.success = function (result) { alert(result); };
    options.error = function (err) { alert(err.statusText); };

    $.ajax(options);

    evt.preventDefault();
});

getting "Undifine" error
Please help me to call ".ashx" file in MVC..

1条回答
Ridiculous、
2楼-- · 2019-09-01 02:41

Take a look at this post below:

How to call a HttpHandler via JQuery in MVC

My recommendation is also to put the entire path into the URL part of the AJAX call where possible as well (e.g. "~/shared/fileuploadhander.ashx").

As Ant P put in the above question, MVC is trying to route the call as an action but the backend is dumb and doesn't know how to handle .ASHX file types (if my understanding is correct).

Also, try putting event.PreventDefault(); at the top of the code. You're in essence saying not to stop the original functionality of the click event then you're calling it again and then you're finally preventing the default functionality (correct me if I am wrong). Try structuring it more like this, it'll stop the event from being fired twice:

$("#btnUpload").click(function (evt) {
  evt.preventDefault();

  var fileUpload = $("#file1").get(0);
  var files = fileUpload.files;

  var data = new FormData();
  for (var i = 0; i < files.length; i++) {
    data.append(files[i].name, files[i]);
  }

  $.ajax({
    url: "FileUploadHandler.ashx",
    type: "POST",
    data: data,
    success: function(data){
       alert(data);
    },
    error: function(err){
       alert(err.statusText);
    }
  });
});
查看更多
登录 后发表回答