2014-02-21 43 views
4

我終於設法使用Ajax來更新我的PartialView。部分視圖的目的是一個側欄小部件,用於顯示註冊內容並允許從註冊中刪除項目。如何優雅地處理禁用JavaScript時的AJAX PartialView更新

的PartialView的簡化版本如下:

<table id="item-entries"> 
    @foreach (var item in Model.Items) 
    { 
     <tr> 
      <td>@item.Name</td> 
      <td>@item.Price</td> 
      <td> 
       @using (Ajax.BeginForm("RemoveItemEntry", "Registration", new AjaxOptions { UpdateTargetId = "item-entries" })) 
       { 
        <button type="submit" name="ItemId" value="@item.ItemId">×</button> 
       } 
      </td> 
     </tr> 
    } 
</table> 

這裏是行動的縮寫例如:

[HttpPost] 
public ActionResult RemoveItemEntry(ItemViewModel data) 
    { 
     // Perform logic to remove the item from the registration 
     // then return the PartialView with updated model 

     return PartialView("~/Views/Partials/ItemEntries.cshtml", model); 
    } 
} 

這個偉大的工程,現在,但是我不想報價對於禁用了JavaScript的用戶而言,這是一個不好的體驗如果您在禁用JavaScript的情況下發布表單,該動作仍然會正確執行,但是您將被重定向到呈現PartialView的網址,而不會顯示其他內容。我想要發生的是,對於JavaScript禁用的用戶,他們會被重定向回發佈表單的原始頁面。

這是可以實現的嗎?

+1

'Request.IsAjaxRequest'可以幫助您決定要渲染哪個視圖。 –

回答

2

所以,你這裏有兩種選擇:

第一個是改變操作方法如下:

[HttpPost] 
public ActionResult RemoveItemEntry(ItemViewModel data) 
{ 
    // Perform logic to remove the item from the registration 
    // then return the PartialView with updated model 

    if (Request.IsAjaxRequest()) 
    { 
      return PartialView("~/Views/Partials/ItemEntries.cshtml", model); 
    } 
    else 
    { 
      // return the initial View not the parial fie 
    } 
} 

第二個選項是會替換正常的那叫一個Ajax表單返回初始View的Action方法。然後,您必須編寫一個jQuery代碼,在提交表單時進行AJAX調用,但它會將AJAX調用返回到PartialView的第二個方法。

+1

對你的解決方案稍作修改,它應該是'''Request.IsAjaxRequest()''' - 你的示例缺少括號。 – ProNotion

+0

謝謝我會解決這個問題。 – ssimeonov

2

我的解決方案去如下 -

在INTIAL視圖中,可以誘導一個cookie如下 -

<script> 
    document.cookie = "JSEnabled=1; path=/"; 
</script> 

那麼對於JS功能的瀏覽器,當你犯了一個POST,cookie將被未來在請求如下 -

enter image description here

當你禁用了JavaScript的瀏覽器,cookie將是空如圖所示低 -

enter image description here

因此,基於該cookie值,無論是空或可用,做一個重定向或返回視圖()按您的要求。

+0

我喜歡你的想法,但沒有意識到'''Request.IsAjaxRequest''檢查@ssimeonov答案,這可能是更適當的方式來執行檢查和處理響應。 – ProNotion

相關問題