3

I need to call a MVC controller function and return back to same view without refreshing the view.
The upload function allows multiple files but I would like to restrict it to 10 files.

Current scenario
I have an upload function on a razor page. The code below calls a "UploadFiles" function.

I would like to return to same page without refreshing it.

 @using (Html.BeginForm("UploadFiles", "Mycontroller", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            @Html.AntiForgeryToken()
            @Html.LabelFor(model => model.files, htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })
            @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })
            <div class="form-group">
            <input type="submit" value="Upload" class="btn btn-primary" />
            </div>
        } 

The controller code is as follows

[HttpPost]
     public ActionResult UploadFiles(HttpPostedFileBase[] files)
        {
            //code inputstream file to bytes
            return View();
        }

I also tried using but it gets redirecting to a different page.

public void UploadFiles(HttpPostedFileBase[] files)
            {
                //code inputstream file to bytes
                return View();
            }
user1339913
  • 1,017
  • 3
  • 15
  • 36
  • 1
    Create a partial view within the main view and load it using ajax-call, so that your whole page will not be refreshed. – Sahil Sharma Jan 09 '19 at 13:05
  • thank you for the reply, I created a partial view. But the HTML.BeginForm does not allow be to call a javascript function – user1339913 Jan 09 '19 at 16:17
  • Not using the Html.BeginForm, using JavaScript/jQuery to perform ajax call on a click event. https://stackoverflow.com/questions/25068431/how-to-call-mvc-action-using-jquery-ajax-and-then-submit-form-in-mvc/25068499 – Sahil Sharma Jan 10 '19 at 05:32

1 Answers1

1

As @Sahil Sharma said before, you need to use AJAX callback to stay in the same page instead of normal form submit with @Html.BeginForm() helper and use a partial view to render the form containing file input element.

You can create FormData object to store multiple files from file input before passing it into AJAX request:

View (form submit button)

<input id="submit" type="submit" value="Upload" class="btn btn-primary" />

jQuery

$('#submit').on('click', function (e) {

    // preventing normal form submit
    e.preventDefault();

    // create new FormData object
    var formData = new FormData();

    // check total amount of uploaded files in file input
    var filesLength = $("#files")[0].files.length;

    // check if the file length exceeds 10 files
    if (filesLength > 10) {
        alert("You can upload at maximum of 10 files");
        return false;
    }
    else {
        // append files to FormData object and send with AJAX callback
        for (var i = 0; i < filesLength; i++) {
            formData.append("files", $("#files")[0].files[i]);
        }

        $.ajax({
            url: '@Url.Action("UploadFiles", "Mycontroller")',
            type: 'POST',
            data: formData,
            // other AJAX options here

            success: function (result) {
                // update partial view here
            }
            error: function (xhr, status, err) {
                // error handling
            }
        });
    }
});

Finally, your controller action should return partial view to update existing part inside view page like this:

[HttpPost]
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
{
    //code inputstream file to bytes

    return PartialView("_YourPartialViewName");
}

Related issues:

Post multiple files by List<HttpPostedFileBase>

HTML5 Multiple File Upload and ASP.Net MVC Ajax

how to upload multiple image in asp.net mvc using ajax

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61