In MVC how to call .ashx handler file through jquery

心已入冬 提交于 2020-01-16 23:11:48

问题


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:


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


来源:https://stackoverflow.com/questions/24076309/in-mvc-how-to-call-ashx-handler-file-through-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!