Submit a Form using AJAX in ASP.Net Core MVC

前端 未结 2 1987
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 10:29

I am working with ASP.Net Core 2.1, and trying to upload a file while returning it\'s url, without refreshing the page.

I am trying to write the JavaScript in site.js a

2条回答
  •  醉梦人生
    2021-02-03 11:24

    Sharing the code that worked for me, implementing @Shyju's answer.

    View ( Razor Page ):

    AJAX code added in Site.js (to make it a reusable):

    // The function takes Form and the event object as parameter
    function SubmitForm(frm, caller) {
    caller.preventDefault();
    
    var fdata = new FormData();
    
    var file = $(frm).find('input:file[name="uploadfile"]')[0].files[0];
    fdata.append("file", file);
    
    $.ajax(
        {
            type: frm.method,
            url: frm.action,
            data: fdata, 
            processData: false,
            contentType: false,
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert(data);
            }
        })
    

    };

提交回复
热议问题