Hello developers.
I come into the situation where I want to upload file with
some other parameters.
My model class is :
public class Banner
{
[Required(ErrorMessage = "Banner Title required", AllowEmptyStrings = false)]
public String Title { get; set; }
[Required(ErrorMessage = "Image required", AllowEmptyStrings = false)]
public HttpPostedFileBase ImageUpload { get; set; }
public String H2 { get; set; }
}
My web api method is as below :
[HttpPost]
public HttpResponseMessage UploadBanner(Admin.Models.Banner banner)
{
if (ModelState.IsValid)
{
return Request.CreateResponse(HttpStatusCode.OK, "Successfully uploaded");
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No elements found");
}
}
My HTML is :
<form id="frmbanner" name="frmbanner" method="post" enctype="multipart/form-data" action="api/Webapi">
@Html.TextBoxFor(model => model.ImageUpload, new { type = "file", id = "ImageUpload", name = "ImageUpload", @class = "default" })
<br/>
@Html.TextBoxFor(model => model.Title, new { id = "Title", name = "Title", @class = "m-wrap span12" })
<br/>
@Html.TextBoxFor(model => model.H2, new { id = "H2", name = "H2", @class = "m-wrap span12" })
<br/>
<button type="submit" id="btnSubmit" class="btn blue"><i class="icon-ok"></i> Save</button>
</form>
From jQuery I am using this method to call web api
$('#btnSubmit').click(function (e) {
e.preventDefault();
var banner = {
Title: $('#Title').val(),
H2: $('#H2').val(),
ImageUpload: $('#ImageUpload')[0].files[0]
};
$.ajax({
type: "POST",
url: "@Url.Action("UploadBanner", "api/Webapi")",
data: JSON.stringify(banner),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function(response) {
alert(response.d);
}
});
});
It passes the string data but its not passing file uploaded, I am uploading image file here.
Please guys help me to do this. I want to upload file with other parameters using ajax call.
Thank you in advance...