I'm still new to how Web API 2.0 works but I'm starting to get the hang of things. The one issue I've been having though is how to post a form along with multiple files that the user uploaded to my controller.
I guess I mainly need help with how to use JavaScript
or jquery
with ajax
to post all of the correct values.
Here is a snippit of my HTML:
<form id="CreateAnnouncementForm" class="form-horizontal">
<input type="hidden" name="announcementTypeID"/>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="col-sm-2 control-label">Headline</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="headline" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">More Info</label>
<div class="col-sm-10">
<textarea class="form-control" name="moreInfo"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Attachments</label>
<div class="col-sm-10">
<input type="file" name="Attachments" multiple/>
</div>
</div>
</div>
</div>
</div>
</form>
Here is the JavaScript/jQuery/Ajax that I normally use to post my form to the controller:
onAnnouncementCreate: function () {
var form = $("#CreateAnnouncementForm");
var validator = $(form).kendoValidator().data("kendoValidator");
if (validator.validate()) {
var options = {
url: getApiUrl() + "/Announcement",
dataType: "json",
type: "POST",
headers: {
"Authorization": "Bearer " + getJwtToken(),
"LocationId": getCurrentLocation()
},
data: $(form).serialize(),
statusCode: {
200: function () {
$("#AnnouncementCreateModal").modal("hide");
announcementViewModel.reloadGrids();
},
400: function (response) {
toastr.options = { "positionClass": "toast-bottom-full-width";
toastr.error(response.responseText);
}
}
};
$.ajax(options);
}
}
Now I believe it would be best if I just created a ViewModel
that contained both the ViewModel
for all of the values in my form and have it contain an IEnumerable
for the attachments that the users can upload within the form.
The trouble I'm having though is correctly adding the attachments to the form so that they map correctly.
My ViewModel
will look like this:
public class AnnouncementCreateViewModel
{
public AnnouncementViewModel Announcement { get; set; }
public IEnumerable<HttpPostedFileBase> Attachments { get; set; }
}
Of course I would then need to change the names in my form to reflect the new model.
If anyone can help me on how to post them to my controller that would be much appreciated as that's the only thing I'm still struggling with.