2014-02-21 45 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

相关问题