user1339913
user1339913

Reputation: 1027

MVC return to same view without refreshing the same view

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

Upvotes: 3

Views: 10593

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

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

Upvotes: 1

Related Questions