Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello developers.

I come into the situation where I want to upload file with
some other parameters.

My model class is :

C#
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 :

SQL
[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) {
                    //code after success

                },
        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...
Posted

1 solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900