How To Send Viewmodel And A File In Single Ajax Post Request, In Mvc 5?
I have an ASP.NET MVC 5 application. And I'm trying to send a POST request with the Model data, and also include user selected files. Here is my ViewModel (simplified for clarity):
Solution 1:
Here is what I test using with MVC5 and IE11 / chrome
View
<script>
$(function () {
$("#form1").submit(function () {
/*You can also inject values to suitable named hidden fields*//*You can also inject the whole hidden filed to form dynamically*/
$('#name2').val(Date);
var formData = newFormData($(this)[0]);
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: formData,
async: false,
success: function (data) {
alert(data)
},
error: function(){
alert('error');
},
cache: false,
contentType: false,
processData: false
});
returnfalse;
});
});
</script><formid="form1"action="/Home/Index"method="post"enctype="multipart/form-data"><inputtype="text"id="name1"name="name1"value="value1" /><inputtype="hidden"id ="name2"name="name2"value="" /><inputname="file1"type="file" /><inputtype="submit"value="Sublit" /></form>
Controller
publicclassHomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file1, string name1, string name2)
{
var result = new List<string>();
if (file1 != null)
result.Add(string.Format("{0}: {1} bytes", file1.FileName, file1.ContentLength));
else
result.Add("No file");
result.Add(string.Format("name1: {0}", name1));
result.Add(string.Format("name2: {0}", name2));
return Content(string.Join(" - ", result.ToArray()));
}
}
Thanks to Silver89 for his answer
Post a Comment for "How To Send Viewmodel And A File In Single Ajax Post Request, In Mvc 5?"