Reputation: 437
I am trying to upload a file in MVC I have used following jquery code to get file on controller.
$(document).ready(function () {
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
});
I have taken this script from here
Its working file but when I want to run some other jquery script thats not firing here the code of that.
function OnUserSuccess() {
if ($("#UserDocumentID").val() == 0) {
mvcNotify.displayMessage("Record saved successfully.", "success");
} else {
mvcNotify.displayMessage("Record updated successfully.", "success");
}
}
I call it in Ajax.begin Form()
@using (Ajax.BeginForm("DocEdit", "User", new { EditUserID = ViewBag.EditUserID }, new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "UserPartialdiv", OnSuccess = "OnUserSuccess" }, new { enctype = "multipart/form-data", @class = "form-sm" }))
I am not much aware of jquery and new to mvc as well please be polite.
Upvotes: 0
Views: 129
Reputation: 9804
Since you have overridden MVC Ajax submit with your javascript submit
function, you can try calling the method in your success call back like this
if (xhr.readyState == 4 && xhr.status == 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
//Call your method here
OnUserSuccess()
}
}
Upvotes: 1
Reputation: 36
Inside the JQuery function, use the
var file = new File();
After this you must be having the button for upload, on it's click event, get the file.
var fileDate = $('#textboxId').value();
and send this fileData via ajax call to controller
$.ajax(type: "POST",
url: '\YourController\yourFunctionName',,
data: { yourParameterNameInControllerFunction : fileData },
success: function() { alert('Success'); },
error: function() {alert('Error')});
your controller should look like this
[HttpPost]
public ActionResult functionName(HttpPostedFileBase file) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/giveyourdirectory"), fileName);
file.SaveAs(path);
}
return RedirectToAction("functionName");
}
this is the basic requirement needed for the upload.
Upvotes: 0