【问题标题】:How to gracefully handle AJAX PartialView update when Javascript is disabled禁用Javascript时如何优雅地处理AJAX PartialView更新
【发布时间】:2014-03-22 23:22:21
【问题描述】:

我终于设法使用 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 的用户,他们将被重定向回发布表单的原始页面。

这可以实现吗?

【问题讨论】:

  • Request.IsAjaxRequest 可以帮助您决定要渲染哪个视图。

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-ajax


【解决方案1】:

我的解决方案如下 -

在初始视图中,您可以如下诱导cookie -

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

那么对于启用了 JS 的浏览器,当您进行 POST 时,cookie 将进入 Request 中,如下所示 -

当你有禁用 JavaScript 的浏览器时,cookie 将为空,如下所示 -

因此,根据该 cookie 值,无论是 null 还是可用,根据您的要求进行重定向或 Return view()。

【讨论】:

  • 我喜欢你的想法,但不知道@ssimeonov 答案中的Request.IsAjaxRequest 签入,这可能是执行检查和处理响应的更合适的方式。
【解决方案2】:

所以你有两个选择:

第一个是将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
    }
}

第二个选项是用一个普通的 Ajax 表单替换你的 Ajax 表单,它调用一个返回初始视图的 Action 方法。然后,您必须编写一个 jQuery 代码,在提交表单时进行 AJAX 调用,但它会对返回 PartialView 的第二个方法进行 AJAX 调用。

【讨论】:

  • 对您的解决方案的小修正,应该是Request.IsAjaxRequest() - 您的示例缺少括号。
  • 谢谢,我会解决的。
猜你喜欢
  • 2011-11-26
  • 2012-04-27
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-08
  • 1970-01-01
  • 2015-03-05
相关资源
最近更新 更多