2009-02-11 50 views
1

我正在運行ASP.NET MVC Beta。我有一個通過jQuery運行的AJAX調用,它抓取我的表單值並將它們發佈到控制器操作。如果我在正常形式的後期場景中沒有AJAX的情況下運行此調用,則所有內容都正確無誤。但是,一旦我加入jQuery代碼,除文件通過之外,所有表單值。 Request.Files()不返回任何內容。是否有一件我在這裏失蹤?從jQuery傳遞到ASP.NET代碼時Request.Files集合爲空

HTML代碼:

<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> 

控制器代碼:

[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代碼:

$(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(); 
} 

回答

1

是啊,這是有道理的,jQuery的連載是不會處理文件上傳數據。你會想看看某種插件來處理文件上傳。我做了一些谷歌搜索它,只發現允許瀏覽按鈕樣式的插件。你可能不得不採取iframe或silverlight路線。

更新 正如註釋中指出的那樣,它們是支持文件上傳的jQuery Form plugin

+0

這些東西對我來說還是一個新東西。我使用jQuery Form插件來實現我需要的結果。謝謝! – 2009-02-11 21:17:01