I'm developing an ASP.NET MVC 4 web application. I'm a beginner in web application. My problem is with file upload and ajax. I have two forms. One of the is for getting the data from user such as name, family and so more. The other one is to upload image. I want the user be able to upload the image before submitting the registration and also see the uploaded image in an <img>
tag. Here is my code:
View
@using (Html.BeginForm("Register", "Customer", FormMethod.Post))
{
<fieldset>
<div class="control-group">
<label class="control-label">Name</label>
<div class="controls">
@Html.TextBoxFor(model => model.Name)
</div>
</div>
<div class="control-group">
<label class="control-label">Family</label>
<div class="controls">
@Html.TextBoxFor(model => model.Family)
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Submit" class="btn btn-info"/>
</div>
</div>
</fieldset>
}
<img src="" class="img"/>
@using (Html.BeginForm("UploadImage", "Customer", FormMethod.Post, new { d="ImageUploadForm", @enctype = "multipart/form-data" }))
{
<input type="file" name="imgfile" class="imgfile"/>
<input type="submit" value="Upload" class="btnUpload btn btn-info" />
}
Action In Controller
[HttpPost]
public string UploadImage(HttpPostedFileBase imgfile)
{
string filePath = "";
if (imgfile != null && imgfile.ContentLength > 0)
{
filePath = Path.Combine(Server.MapPath("~/Customer/"), imgfile.FileName);
imgfile.SaveAs(filePath);
}
return "~/Customer/" + imgfile.FileName;
}
Javascript
$('#ImageUploadForm').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('.img').attr('src', result);
}
})
return false;
}
});
Now the problem is that when I select a file and hit the Upload
button, the UploadImage()
action is called and file is uploaded, but the success event of ajax is not called and it redirects me to another page called localhost/Customer/UplaodImage
it's content is just the file path that UploadImage
had returned. Is it ever possible to do this? Or I cant post a form data using ajax and not redirecting to another page? Any help is appreciated.