【问题标题】:MVC3 Ajax.BeginForm with javascript disabled禁用 javascript 的 MVC3 Ajax.BeginForm
【发布时间】:2011-05-09 03:56:06
【问题描述】:

在没有启用 javascript 的情况下让表单工作时遇到问题。

这应该足够继续了,问你是否需要知道其他任何事情 - 我不想把整个解决方案都放在这里!

~/Views/_ViewStart.cshtml:

@{ Layout = "~/Views/Shared/Layout.cshtml"; }

~/Views/Shared/Layout.cshtml:

@using System.Globalization; @{ CultureInfo culture = CultureInfo.GetCultureInfo(UICulture); }<!DOCTYPE html>
<html lang="@culture.Name" dir="@(culture.TextInfo.IsRightToLeft ? "rtl" : "ltr")">
<head>
  <title>AppName :: @ViewBag.Title</title>
  <link href="@Url.Content("~/favicon.ico")" rel="shortcut icon" type="image/x-icon" />
  <link href="@Url.Content("~/apple-touch-icon.png")" rel="apple-touch-icon" />  
  <link href="@Url.Content("~/Content/css/site.css")" rel="stylesheet" type="text/css" />
  <script src="@Url.Content("~/Content/js/jquery-1.6.min.js")" type="text/javascript"></script>
  <script src="@Url.Content("~/Content/js/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
  <script src="@Url.Content("~/Content/js/jquery.validate.min.js")" type="text/javascript"></script>
  <script src="@Url.Content("~/Content/js/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
  <script src="@Url.Content("~/Content/js/app.js")" type="text/javascript"></script>
  @RenderSection("SectionHead", false)
</head>
<body>
  <div id="page-container">
    <div id="nav">
      <div id="nav-user">
        @{ Html.RenderAction("LoginStatus", "Account"); }
        @{ Html.RenderPartial("CultureSelector"); }
      </div>
    </div>
    <div id="page-content">
      <h2>@ViewBag.Title</h2>
      @RenderBody()
    </div>
  </div>
</body>
</html>

~/Views/Account/Index.cshtml:

@model AccountFilterModel
@{ 
  ViewBag.Title = "Account Home";
  var loadingId = "loading" + new Random().Next();
  Model.FilterFormId = "filter-account-form";
}
@using (Ajax.BeginForm("List", "Account", Model, new AjaxOptions { UpdateTargetId = "result-list", LoadingElementId = loadingId }, new { id = "filter-account-form" })) {
  <!-- form controls and validation summary stuff -->
  <input id="filter" type="submit" value="Filter" />
  <span id="@loadingId" style="display: none">
    <img src="@Url.Content("~/Content/images/ajax-loader.gif")" alt="Loading..." />
  </span>
}
<div id="result-list">
  @{ Html.RenderAction("List", Model); }
</div>

~/Views/Account/List.cshtml:

@model FilterResultModel
@helper SortLink(AccountSort sort, SortDirection dir) {
  string display = (dir == SortDirection.Ascending ? "a" : "d"); // TODO: css here
  if (Model.Filter.SortBy != null && ((AccountSortModel)Model.Filter.SortBy).Sort == sort && dir == Model.Filter.SortOrder) {
    @:@display
  } else {
    FilterModel fm = new FilterModel(Model.Filter);
    fm.SortBy = AccountSortModel.SortOption[sort];
    fm.SortOrder = dir;
    <a href="@Url.Action("Index", "Account", fm.GetRouteValueDictionary())" onclick="@(string.Format("setFormValue('{0}', '{1}', '{2}'); setFormValue('{0}', '{3}', '{4}'); formSubmit('{0}'); return false;", Model.Filter.FilterFormId, Html.PropertyNameFor(x => x.Filter.SortOrder), dir, "AccountSort", sort))">@display</a>
  }
}

@if (Model.Results.Count > 0) {
  var first = Model.Results.First();
  <table>
    <caption>
      @string.Format(LocalText.FilterStats, Model.FirstResultIndex + 1, Model.LastResultIndex + 1, Model.CurrentPageIndex + 1, Model.LastPageIndex + 1, Model.FilteredCount, Model.TotalCount)
    </caption>
    <thead>
      <tr>
        <th>
          @Html.LabelFor(m => first.Username)
          <span class="sort-ascending">
            @SortLink(AccountSort.UsernameLower, SortDirection.Ascending)
          </span>
          <span class="sort-descending">
            @SortLink(AccountSort.UsernameLower, SortDirection.Descending)
          </span>
        </th>
        <!-- other table headers -->
      </tr>
    </thead>
    <tbody>
      @foreach (AccountModel account in Model.Results) {
        <tr>
          <td>@Html.EncodedReplace(account.Username, Model.Filter.Search, "<span class=\"filter-match\">{0}</span>")</td>
          <!-- other columns -->
        </tr>
      }
    </tbody>
  </table>
  Html.RenderPartial("ListPager", Model);
} else {
  <p>No Results</p>
}

AccountController.cs 的相关部分:

public ActionResult Index(AccountSort? accountSort, FilterModel model = null) {
  FilterModel fm = model ?? new FilterModel();
  if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
  return View(fm);
}

public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
  FilterModel fm = model ?? new FilterModel();
  if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
  return Request.IsAjaxRequest() ? (ActionResult)PartialView("List", Service.Get(fm)) : View("Index", model);
}

启用 javascript 后,一切正常 - div#result-list 的内容按预期更新。

如果我不执行Request.AjaxRequest() 而只返回PartialView,那么在禁用javascript 的情况下,我会得到一个仅包含结果内容的页面。如果我有上面的代码,那么我会得到一个StackOverflowException

如何让它工作?

解决方案

感谢@xixonia,我发现了问题 - 这是我的解决方案:

public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
  FilterModel fm = model ?? new FilterModel();
  if (accountSort.HasValue) 
    fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
  if (Request.HttpMethod == "GET")
    return PartialView("List", Service.Get(fm));
  if (Request.HttpMethod == "POST")
    return Request.IsAjaxRequest() ? (ActionResult) PartialView("List", Service.Get(fm)) : RedirectToAction("Index", model);
  return new HttpStatusCodeResult((int) HttpStatusCode.MethodNotAllowed);
}

【问题讨论】:

    标签: ajax asp.net-mvc-3 c#-4.0 javascript


    【解决方案1】:

    可以使用下面的扩展方法来判断请求是否为ajax请求

    Request.IsAjaxRequest()
    

    如果是,则可以返回部分视图,否则可以返回完整视图或重定向。

    if(Request.IsAjaxRequest())
    {
        return PartialView("view", model);
    }
    else
    {
        return View(model);
    }
    

    编辑:问题出在:

    当请求不是 AJAX 请求时,“列表”正在返回“索引”视图:

    public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
      FilterModel fm = model ?? new FilterModel();
      if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
      return Request.IsAjaxRequest() ? (ActionResult)PartialView("List", Service.Get(fm)) : View("Index", model);
    }
    

    “索引”视图正在渲染“列表”操作:

    @{ Html.RenderAction("List", Model); }
    

    又名:递归。

    您需要设计一种方法来显示您的列表而不绘制索引页面,或者让您的索引页面以列表模式作为参数绘制部分视图。

    【讨论】:

    • 是的,我也是这么想的,我也试过了,但是我得到了 StackOverflowException,因为最初的 GET 不是 ajax 的(我假设),所以它一直在尝试做一个整页响应在自身内部。
    • 当您的布局在需要布局的视图上使用 Html.View 或 Html.RenderView 时,通常会发生堆栈溢出异常。这将导致布局和视图的递归渲染......这篇文章中没有足够的信息来确定堆栈溢出异常的原因,但是使用 Request.IsAjax 的正确方法你在问什么。您能否发布您遇到的堆栈溢出异常以及布局、控制器、操作等问题?让我们解决问题,而不是尝试创建解决方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 2016-03-06
    相关资源
    最近更新 更多