繁体   English   中英

如何在禁用Javascript时优雅地处理AJAX PartialView更新

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM