[英]How to gracefully handle AJAX PartialView update when Javascript is disabled
我終於設法使用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的URL,而不是其他任何內容。 我想要發生的是,對於禁用JavaScript的用戶,他們會被重定向回發布表單的原始頁面。
這可以實現嗎?
我的解決方案如下 -
在初始視圖中,您可以按如下方式誘導cookie -
<script>
document.cookie = "JSEnabled=1; path=/";
</script>
然后對於啟用JS的瀏覽器,當您進行POST時,cookie將進入請求,如下所示 -
當您禁用JavaScript瀏覽器時,cookie將為null,如下所示 -
因此,基於該cookie值,無論是null還是可用,根據您的要求進行重定向或返回視圖()。
所以你有兩個選擇:
第一個是將Action方法更改為以下內容:
[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
}
}
第二個選項是使用調用返回初始View的Action方法的法線替換Ajax窗體。 然后你必須編寫一個jQuery代碼,在提交表單時進行AJAX調用,但是它會調用另一個返回PartialView的方法的AJAX。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.