Introduction :
This article
introduce an example of Asp.Net MVC project to post the form data including
File uploading (Collectively) through Ajax and Jquery.
Background :
You can find many examples of file uploading through Ajax-Jquery in MVC but if you want to post a form data which includes a file also to be uploaded then those articles doesn't suit your requirement, and people who use "Ajax.BeginForm()" to post the form through Ajax also can't be able to get the files to be uploaded on POST Action. So this example describe a simple approach to accomplish this requirement.
Tools and Library Used:
1. Visual Studio 2013
2. MVC5
3. jquery-1.10.2
The Model :
To get started with
this first we have to define a model which we want to post through our form :
public class TestModel
{
public string Name { get; set;}
public string Surname { get; set; }
}
We have defined a
model (class) which consists two string type properties which we are going to
submit through form.
The View :
@model
TestUpload.Models.TestModel
@using (Html.BeginForm("UFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "Myform" }))
{
@Html.TextBoxFor(c=>c.Name)
@Html.TextBoxFor(c=>c.Surname)
<input type="file" id="myfile" name="myfile" multiple />
<button id="myBtn" type="button">Submit</button>
}
<script>
$(document).ready(function () {
$("#myBtn").click(function () {
var formData = new FormData($("form#Myform")[0]);
// send
them to server
$.ajax({
type: "POST",
url: '@Url.Action("UFile", "Home")',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert(response);
},
error: function (error) {
alert(error.message);
}
});
});
});
</script>
We have defined a
view called "UFile .cshtml" which is bounded by
our "TestModel", contains two text boxes and one file upload control
which can accept multiple files. All the element are in the scope of a form
"Html.BeginForm" not "Ajax.BeginForm". Now there is a
button, on the button click we want to save the entered data of text box in
database and also want to upload and save the files to our local directory, and
most importantly all this work should be asynchronous(No-Post back). So in
Script we have used $.ajax to post this data asynchronously. Now look at the highlighted line, this is
the bunch of words which is doing all the magic for us. From this line we
can get all the form data serialized in a model and all the files in
HttpRequest object. Except this line nothing is new, we are just giving a url
to call. If you are not familiar with @Url.Action then it is just taking two
parameters and it will automatically generate the url for you. First argument
in for "Action Name" and Second argument is for "Controller
Name". Now have a look at the Action defined in the Home Controller.
The Controller:
public class HomeController : Controller
{
public ActionResult UFile()
{
return View();
}
[HttpPost]
public ActionResult UFile(TestModel model)
{
//
Get All the files in request variable.
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Upload/"), fileName);
file.SaveAs(path);
}
return Json("You Did it
"+string.Format("{0}
{1}",model.Name,model.Surname));
}
}
We have a controller called "Home" there are
two Actions of same name with different arguments. One is for initial view
rendering(the view which we have already described). And the second annotated
with [HttpPost] is the action which is being called by the Ajax Script we have
defined on our view. The action is self-explanatory, you can notice the
highlighted portion in "Request.Files",
you will get all the files which you have browsed before clicking the
submit button and "Model.Name"
and "Model.Surname" will give you the value of textboxes you have
entered before clicking the submit button.
To get started with this first we have to define a model which we want to post through our form :
public class TestModel
{
public string Name { get; set;}
public string Surname { get; set; }
}
We have defined a model (class) which consists two string type properties which we are going to submit through form.
The View :
@model
TestUpload.Models.TestModel
@using (Html.BeginForm("UFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "Myform" }))
{
@Html.TextBoxFor(c=>c.Name)
@Html.TextBoxFor(c=>c.Surname)
<input type="file" id="myfile" name="myfile" multiple />
<button id="myBtn" type="button">Submit</button>
}
<script>
$(document).ready(function () {
$("#myBtn").click(function () {
var formData = new FormData($("form#Myform")[0]);
// send
them to server
$.ajax({
type: "POST",
url: '@Url.Action("UFile", "Home")',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert(response);
},
error: function (error) {
alert(error.message);
}
});
});
});
</script>
We have defined a
view called "UFile .cshtml" which is bounded by
our "TestModel", contains two text boxes and one file upload control
which can accept multiple files. All the element are in the scope of a form
"Html.BeginForm" not "Ajax.BeginForm". Now there is a
button, on the button click we want to save the entered data of text box in
database and also want to upload and save the files to our local directory, and
most importantly all this work should be asynchronous(No-Post back). So in
Script we have used $.ajax to post this data asynchronously. Now look at the highlighted line, this is
the bunch of words which is doing all the magic for us. From this line we
can get all the form data serialized in a model and all the files in
HttpRequest object. Except this line nothing is new, we are just giving a url
to call. If you are not familiar with @Url.Action then it is just taking two
parameters and it will automatically generate the url for you. First argument
in for "Action Name" and Second argument is for "Controller
Name". Now have a look at the Action defined in the Home Controller.
The Controller:
public class HomeController : Controller
{
public ActionResult UFile()
{
return View();
}
[HttpPost]
public ActionResult UFile(TestModel model)
{
//
Get All the files in request variable.
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Upload/"), fileName);
file.SaveAs(path);
}
return Json("You Did it
"+string.Format("{0}
{1}",model.Name,model.Surname));
}
}
We have a controller called "Home" there are
two Actions of same name with different arguments. One is for initial view
rendering(the view which we have already described). And the second annotated
with [HttpPost] is the action which is being called by the Ajax Script we have
defined on our view. The action is self-explanatory, you can notice the
highlighted portion in "Request.Files",
you will get all the files which you have browsed before clicking the
submit button and "Model.Name"
and "Model.Surname" will give you the value of textboxes you have
entered before clicking the submit button.
The Controller:
public class HomeController : Controller
{
public ActionResult UFile()
{
return View();
}
[HttpPost]
public ActionResult UFile(TestModel model)
{
//
Get All the files in request variable.
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Upload/"), fileName);
file.SaveAs(path);
}
return Json("You Did it
"+string.Format("{0}
{1}",model.Name,model.Surname));
}
This comment has been removed by the author.
ReplyDeleteLifeVoxel.AI platform offers a better alternative for the medical imaging community. Its unique approach is based on 12 international patents that encompass critical patient-centric delivery of care using intuitive, diagnostic and instantly accessible visualizations over the Internet. It works 100X faster and 42-80% cheaper than all our competitors.
ReplyDeleteInteractive Streaming and Artificial Intelligence Platform