I am running ASP.NET MVC Beta. I have an AJAX call running through jQuery which grabs my form values and posts them to a controller action. If I run this call without AJAX in a normal form post scenario, everything comes through correctly. However, once I incorporate the jQuery code, all the form values EXCEPT the files come through. Request.Files() returns nothing. Is there an additional piece I am missing here?
HTML code:
<form action="/Images/AddImages/" enctype="multipart/form-data" id="frmAddImages" method="post">
<%=Html.Hidden("hfPromoId",ViewData.Model.Promotion.PromoId) %>
<table>
<tr>
<td>Images for Promo: </td>
<td><span class="promoTitle"><%=Html.Encode(ViewData.Model.Promotion.PromoName) %></span></td>
</tr>
<tr class="newImageContainer">
<td>Select Image:</td>
<td>
<input type="file" id="txtImagePath" name="txtImagePath" />
</td>
</tr>
<tr class="newImageContainer">
<td>Image Caption:</td>
<td>
<input id="txtImageCaption" name="txtImageCaption" />
</td>
</tr>
<tr>
<td><input type="submit" value="Save Image" id="AddImages" /></td>
</tr>
</table>
</form>
Controller code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddImages(bool? partial)
{
int promoId = Convert.ToInt32(Request.Form["hfPromoId"]);
var promo = _promoRepository.GetPromotion(promoId);
string imageCaption = Request.Form["txtImageCaption"].ToString();
string imagePath = string.Empty;
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
{ continue; }
imagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"Content\PromoImages",
promo.PromoId.ToString() + "__" + Guid.NewGuid().ToString() + Path.GetFileName(hpf.FileName));
hpf.SaveAs(imagePath);
}
_promoRepository.SaveImageForPromo(promoId, imageCaption, imagePath, this.Request);
if (partial == true)
{
return List(true, promoId);
}
return View("Images", GetModel(promoId));
}
jQuery code:
$(document).ready(function() {
$('#frmAddImages').submit(function() {
runAjax(form, updateImageList, 'html');
return false;
});
});
function runAjax(form, callback, format) {
$.ajax({
url: form.action + '?partial=true',
type: form.method,
dataType: format,
data: $(form).serialize(),
success: callback
});
}
function updateImageList(result) {
$('#gallery').html(result);
setElementStyling();
}