禁用javascript的MVC3 Ajax.BeginForm

时间:2011-05-09 03:56:06

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

我无法在没有启用javascript的情况下使表单正常工作。

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

〜/查看/ _ViewStart.cshtml:

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

〜/查看/共享/ 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>

〜/查看/帐户/ 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>

〜/查看/帐户/ 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);
}

1 个答案:

答案 0 :(得分:2)

您可以使用以下扩展方法来确定请求是否为ajax请求

Request.IsAjaxRequest()

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

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

编辑:问题在于:

当请求不是AJAX请求时,“List”返回“Index”视图:

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); }

AKA:递归。

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