MVC 5 prevent page refresh on form submit

筅森魡賤 提交于 2021-01-04 07:43:45

问题


yBrowser: IE9 Technologies: MVC5

I am mainly using Angular for everything on my page. (Single Page App).

But because I am working with IE9, I can't use FileAPI.. So, I decided to go with MVC's Form Actions to get HttpPostedFileBase in my controller methods to handle fileupload.

Html Code: (Is present in a modal)

@using (Html.BeginForm("UploadTempFileToServer", "Attachment", FormMethod.Post, new { enctype = "multipart/form-data", id = "attachmentForm" }))
{
    <div>
        <span id="addFiles" class="btn btn-success fileinput-button" ng-class="{disabled: disabled}" onclick="$('#fileUpload').click();">
            <span>Add files...</span>
        </span>
        <input id="fileUpload" type="file" name="files" class="fileInput" onchange="angular.element(this).scope().fileAdded(this)" />
    </div>
    <div>
        <span class="control-label bold">{{currentFilePath}}</span>
        <input name="fileUniqueName" value="{{fileUniqueName}}" />
        <input id="attachmentSubmit" type="submit" value="Upload File" />
    </div>
}

MVC Controller:

public void UploadTempFileToServer(IEnumerable<HttpPostedFileBase> files, string fileUniqueName)
    {
        var folderPath = fileStorageFolder;

        foreach (var file in files)
        {
            if (file.ContentLength > 0)
            {
                file.SaveAs(folderPath + fileUniqueName);
            }
        }
    }

Question #1: Does anyone know of a way to send the HttpPostedFileBase data to the controller, without using form's submit action?

I don't mind using Jquery if need be. I have tried hijacking the form's submit action and that didn't work. I tried sending the file control's data using non submit button event, but no luck there either.

If not:

Question #2 How do I prevent the page from going to /Attachment/UploadTempFileToServer after the execution of submit is completed?


回答1:


To answer #2 (and assuming you're using jQuery):

$(document).on('submit', '#attachmentForm', function(event){

    event.preventDefault();

    // everything else you want to do on submit
});

For #1, unfortunately, unless a browser supports XMLHttpRequest2 objects (which I don't believe IE9 does), you can't send file data via ajax. There are plugins that let you submit the form to a hidden iframe, though. I think Mike Alsup's Form plugin has that ability: http://malsup.com/jquery/form/#file-upload




回答2:


So, after much research and attempts. This is my solution:

Using https://github.com/blueimp/jQuery-File-Upload/wiki

HTML:

Earlier I was using a hidden file upload control and triggering its click via a span. But because of security issues a file input which is opened by javascript can't be submitted by javascript too.

<div class="col-md-7">
    <div class="fileupload-buttonbar">
        <label class="upload-button">
            <span class="btn btn-success btnHover">
                <i class="glyphicon glyphicon-plus"></i>
                <span>Add files...</span>
                <input id="fileUpload" type="file" name="files"/>
            </span>
        </label>
     </div>
</div>

Javascript:

$('#fileUpload').fileupload({
    autoUpload: true,
    url: '/Attachment/UploadTempFileToServer/',
    dataType: 'json',
    add: function (e, data) {
        var fileName = data.files[0].name;
        var ext = fileName.substr(fileName.lastIndexOf('.'), fileName.length);

        var attachment = {
            AttachmentName: fileName,
            Extension: ext
        }

        var fileUniqueName = id + ext;

        //Sending the custom attribute to C#
        data.formData = {
            fileUniqueName: fileUniqueName
        }

        data.submit().success(function (submitData, jqXhr) {
            attachment.Path = submitData.path;

            //Add the attachment to the list of attached files to show in the table.
            $scope.attachmentControl.files.push(attachment);
            //Since this is not a direct angular event.. Apply needs to be called for this to be bound to the view.
            $scope.$apply();

        }).error(function (errorData, textStatus, errorThrown) {

        });
    },
    fail: function (data, textStatus, errorThrown) {

    }
});

C#:

public virtual ActionResult UploadTempFileToServer(string fileUniqueName)
    {
        //Getting these values from the web.config.
        var folderPath = fileStorageServer + fileStorageFolder + "\\" + tempFileFolder + "\\";

        var httpPostedFileBase = this.Request.Files[0];
        if (httpPostedFileBase != null)
        {
            httpPostedFileBase.SaveAs(folderPath + fileUniqueName);
        }
        return Json(new
            {
                path = folderPath + fileUniqueName
            },
            "text/html"
        );
    }


来源:https://stackoverflow.com/questions/25277499/mvc-5-prevent-page-refresh-on-form-submit

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