Below I have the relevant code parts for my AJAX image upload for my MVC4 ASP.Net application. However when I click on the upload link it simply appends an # to the end of my URL link so http://localhost:10991/StoreManager/Create# and goes to the top of the page.
There are no errors I can see appearing in the Debugger or console window.
I have used the code from here
http://powerdotnetcore.com/asp-net-mvc/asp-net-mvc-simple-ajax-file-upload-using-jquery
_PartialView
@model SwitchClothing.Models.Image
<script src="~/Scripts/jquery-2.1.0.min.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/FileUpload/jquery.fileupload.js"></script>
<script src="~/Scripts/FileUpload/jquery.fileupload-ui.js"></script>
<script src="~/Scripts/FileUpload/jquery.iframe-transport.js"></script>
<script src="~/Scripts/upload.js"></script>
<div class="well">
<div>
<h1>Upload by click</h1>
</div>
<div>@Html.TextBoxFor(m => m.MyFile, new { id = "fu-my-simple-upload", type = "file" }) <a href="#" id="hl-start-upload">Start upload</a> </div>
</div>
Upload.js
var jqXHRData;
$(document).ready(function () {
initSimpleFileUpload();
$("#hl-start-upload").on('click', function () {
if (jqXHRData) {
jqXHRData.submit();
}
return false;
});
});
function initSimpleFileUpload() {
'use strict';
$('#fu-my-simple-upload').fileupload({
url: '/File/UploadFile',
dataType: 'json',
add: function (e, data) {
jqXHRData = data
},
done: function (event, data) {
if (data.result.isUploaded) {
}
else {
}
alert(data.result.message);
},
fail: function (event, data) {
if (data.files[0].error) {
alert(data.files[0].error);
}
}
});
}
Controller Action
[HttpPost]
public virtual ActionResult UploadFile()
{
HttpPostedFileBase myFile = Request.Files["MyFile"];
bool isUploaded = false;
string message = "File upload failed";
if (myFile != null && myFile.ContentLength != 0)
{
string pathForSaving = Server.MapPath("~/Images");
if (this.CreateFolderIfNeeded(pathForSaving))
{
try
{
myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
isUploaded = true;
message = "File uploaded successfully!";
}
catch (Exception ex)
{
message = string.Format("File upload failed: {0}", ex.Message);
}
}
}
return Json(new { isUploaded = isUploaded, message = message }, "text/html");
}
private bool CreateFolderIfNeeded(string path)
{
bool result = true;
if (!Directory.Exists(path))
{
try
{
Directory.CreateDirectory(path);
}
catch (Exception)
{
/*TODO: You must process this exception.*/
result = false;
}
}
return result;
}
Rendering the partial view in the Create page of model view
@RenderPage("_Upload.cshtml")