Upload file/image and other data using jQuery AJAX call In MVC
In given example we will show that how to uploads file along with other data in single call.
This project is in MVC, so first of all you have to create a MVC project.
Here are some steps to create MVC project to send data to controller using jQuery AJAX call.
Step - 1:
Create MVC project and write following code in to Index.cshtml page.
<div class="row">
<div class="col-md-12">
<form id="addcompanydata" enctype="multipart/form-data" method="post">
<div class="col-lg-12 col-md-12 col-sm-12">
<fieldset>
<legend>Profile Detail </legend>
<div class="form-group row">
<label for="inputPassword3" class="col-sm-3 form-control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="name" name="name" required="" maxlength="50"
data-toggle="First Name" data-placement="top" data-html="true" title="First name">
</div>
</div>
<div class="form-group row">
<label for="inputPassword3" class="col-sm-3 form-control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control" id="email" name="email" required=""
data-toggle="tooltip" data-placement="top" data-html="true" title="Email-Id must be <br> in this format 'john@host.web'" />
</div>
</div>
<div class="form-group row">
<label for="inputPassword3" class="col-sm-3 form-control-label">Password</label>
<div class="col-sm-9">
<input type="password" class="form-control" id="password" name="password" required
data-toggle="tooltip" data-placement="top" data-html="true" title="Email-Id must be <br> in this format 'john@host.web'" />
</div>
</div>
<div class="form-group row">
<label for="inputPassword3" class="col-sm-3 form-control-label">Gender</label>
<div class="col-sm-9">
<input type="radio" name="gender" value="male" checked> Male
<input type="radio" name="gender" value="female"> Female<br>
</div>
</div>
<div class="form-group row">
<label for="inputPassword3" class="col-sm-3 form-control-label">Profile</label>
<div class="col-sm-9 addlogo">
<div class="avatar">
<input type="hidden" id="fileName" />
<div class="kv-avatar center-block">
<input id="imgupload" name="imgupload" type="file" class="file-loading" required accept="image/jpg,image/png,image/jpeg" />
</div>
</div>
</div>
</div>
</fieldset>
<div class="clearfix"> </div>
</div>
<br/>
<div class="col-md-3"></div>
<div class="col-md-9 col-sm-12">
<button type="reset" id="rst" class="btn btn-info">Reset</button>
<button type="submit" class="btn btn-primary" id="addprofile" value="">Submit</button>
</div>
</form>
</div>
</div>
[HttpPost]
public JsonResult AddProfile(UserProfile userDetail)
{
var profile = Request.Files;
string imgname = string.Empty;
string ImageName = string.Empty;
//Following code will check that image is there
//If it will Upload or else it will use Default Image
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var logo = System.Web.HttpContext.Current.Request.Files["file"];
if (logo.ContentLength > 0)
{
var profileName = Path.GetFileName(logo.FileName);
var ext = Path.GetExtension(logo.FileName);
ImageName = profileName;
var comPath = Server.MapPath("/Images/") + ImageName;
logo.SaveAs(comPath);
userDetail.Profile = comPath;
}
}
else
userDetail.Profile = Server.MapPath("/Images/") + "profile.jpg";
int response = 1;
return Json(response, JsonRequestBehavior.AllowGet);
}
Step – 2:
Create controller to which we are sending our data, it could be anything like image or text.
Here is our controller code:
Here before action we have written HttpPost because we send data through post method in AJAX call.
Step – 3:
Create an AJAX call as given below and main thing is in our AJAX call is FormData. It is useful to transfer data from AJAX call to our controller.
This code is written in "Script.js" in "/Scripts" Folder.
To use this code we have to include it in to "_Layout.cshtml" after all other script.
We can also include it in "BundleConfig.cs".
$(document).ready(function () {
$('#addprofile').click(function () {
var formData = new FormData();
var files = $("#imgupload").get(0).files;
formData.append("file", files[0]);
formData.append("FirstName", $('#name').val());
formData.append("Email", $('#email').val());
formData.append("Password", $('#password').val());
formData.append("Gender", $("input[name='gender']:checked").val());
formData.append("Profile", files[0].name);
$.ajax({
type: 'POST',
url: "/Home/AddProfile",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (response) {
if (response == 1) {
alert("successfully Profile Updated");
}
else {
alert("Something Went Wrong..");
}
}
})
})
})
Step – 4:
Execution:
Index.cshtml
After fillup the form click on submit button.
And use debugger in c# code to view the details.
Here as we can see that our all the data is available in "userDetail" object.
Now we can use this object to insert data in to database also.
After data reached here it will show you successfull Message.
This project main focus is to bring data and file in single call and store it in to Database.
Here I have not included the CRUD Operation.
Ajit
4/19/2017Oops - sorry. Clicked on that 'post comment' couple of times. Did not see it appearing above.
Nikhil Varghane
7/25/2020Thanks for explanation and code, No article has explained about image upload with other data.
Ajit
4/19/2017Thanks. Very neat explanation.