Ajax.BeginForm(...) 并不总是有效,有时完全回发,使用 ASP.NET MVC

Posted

技术标签:

【中文标题】Ajax.BeginForm(...) 并不总是有效,有时完全回发,使用 ASP.NET MVC【英文标题】:Ajax.BeginForm(...) not always working, full postback sometimes, using ASP.NET MVC 【发布时间】:2011-07-26 12:30:41 【问题描述】:

我这辈子都想不通为什么这个回发有时会像它应该做的那样做一个 ajax,而有时却没有。以下是相关代码:

JS:

<html>
<head>
<title>Index</title>
<link href="/Content/screen.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 8]><link href="/Content/ie.css" rel="stylesheet" type="text/css" /><![endif]-->
<link href="/Content/plugins/fancy-type/screen.css" rel="stylesheet" type="text/css" />
<link href="/Content/plugins/buttons/screen.css" rel="stylesheet" type="text/css" />
<link href="/Content/plugins/link-icons/screen.css" rel="stylesheet" type="text/css" media="screen, projection" />
<link href="/Content/jQueryUI/css/cupertino/jquery-ui-1.8.9.custom.css" rel="stylesheet" type="text/css" />
<link href="/Content/HelpDesk.css" rel="stylesheet" type="text/css" />
<link href="/Content/droppy.css" rel="stylesheet" type="text/css" />
<link href="/Content/tablesorter.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="/Scripts/jquery.droppy.js" type="text/javascript"></script>
<script src="/Scripts/jquery.cascadingDropDown.js" type="text/javascript"></script>
<script src="/Scripts/jquery.tablesorter.min.js" type="text/javascript"></script>
<script type='text/javascript'>
    $(function () 
        $('#nav').droppy();
    );
</script>
<script type="text/javascript">
        $(document).ready(function () 
            $("#targetStartDate").datepicker();
            $("#targetEndDate").datepicker();
            $("#ticketsHTMLTable").tablesorter( sortList: [[0, 0], [1, 0]] );
            $(".fakeLink").mouseover(function () 
                $(this).css("color", "red");
            );
            $(".fakeLink").mouseout(function () 
                $(this).css("color", "black");
            );
        );
</script>
</head>

这是我的观点(剃刀):

@using (Ajax.BeginForm("Index", "Problem", new AjaxOptions

    HttpMethod = "GET",
    UpdateTargetId = "ticketsTable",
    InsertionMode = InsertionMode.Replace

))

       <div class="notice">
        <div class="prepend-1 span-2">
            <label for="targetPriorityID">
                Priority</label>
        </div>
        <div class="prepend-1 span-3">
            <label for="targetStatusID">
                Status</label>
        </div>
        <div class="span-3">
            <label for="targetBusinessUnitID">
                Business Unit</label>
        </div>
        <div class="span-3 prepend-1">
            <label for="targetStartDate">
                Start Date</label></div>
        <div class="span-3 prepend-2">
            <label for="targetEndDate">
                End Date</label></div>
        <div class="prepend-1 span-3 last">
            &nbsp
        </div>        <div class="prepend-1 span-2">
            @Html.DropDownList("targetPriorityID",
new SelectList(ViewBag.Priorities as System.Collections.IEnumerable,
"ID", "Title"), "All", new  @onchange = " this.form.submit();" )
        </div>
        <div class="prepend-1 span-3">
            @Html.DropDownList("targetStatusID",
new SelectList(ViewBag.Statuses as System.Collections.IEnumerable,
       "ID", "Title"),"All", new  @onchange="this.form.submit();" )
        </div>
        <div class="span-3">
            @Html.DropDownList("targetBusinessUnitID",
new SelectList(ViewBag.BusinessUnits as System.Collections.IEnumerable,
       "ID", "Title"), "All", new  @onchange = "this.form.submit();" )
        </div>

        <div class="span-3 prepend-1">@Html.TextBox("targetStartDate", "", new  onchange = "this.form.submit();" )</div>
        <div class="span-3 prepend-2">@Html.TextBox("targetEndDate", "", new  onchange = "this.form.submit();" )</div>
        <div class="prepend-1 span-3 last">
            <input type="submit" value="Hide" />
        </div>
        <br />
        <br />
        <br />
    </div>

<div id="ticketsTable">
    @Html.Partial("_AllTickets", Model)
</div>

最后是控制器,

    [HttpPost]
    public ActionResult Index(int targetPriorityID = -1, int targetBusinessUnitID = -1, int targetStatusID = -1, string targetStartDate = "", string targetEndDate ="")
    
        Repository<Priority> priorityRepository = new Repository<Priority>();
        Repository<BusinessUnit> businessUnitRepository = new Repository<BusinessUnit>();
        Repository<Status> statusRepository = new Repository<Status>();

        ViewBag.Priorities = priorityRepository.GetAll();
        ViewBag.BusinessUnits = businessUnitRepository.GetAll();
        ViewBag.Statuses = statusRepository.GetAll();

        var results = problemRepository.GetAll();

        results = (targetPriorityID != -1) ? results.Where(t => t.PriorityID == targetPriorityID) : results;
        results = (targetBusinessUnitID != -1) ? results.Where(t => t.BusinessUnitID == targetBusinessUnitID) : results;
        results = (targetStatusID != -1) ? results.Where(t => t.StatusID == targetStatusID) : results;
        results = (targetStartDate != "") ? results.Where(t => t.DateReported >= DateTime.Parse(targetStartDate)) : results;
        results = (targetEndDate != "") ? results.Where(t => t.DateReported <= DateTime.Parse(targetEndDate)) : results;


        if (Request.IsAjaxRequest())
        
            return PartialView("__AllTickets", results);
        

        return View(results);

    

有什么想法吗?

【问题讨论】:

原来是这一行在表中没有结果时被炸掉了 $("#ticketsHTMLTable").tablesorter( sortList: [[0, 0], [1, 0]] ); 【参考方案1】:

我建议您使用稍后将被 AJAX 化的普通格式:

@using (Html.BeginForm("Index", "Problem")

    <div class="notice">
        <div class="prepend-1 span-2">
            <label for="targetPriorityID">Priority</label>
        </div>
        <div class="prepend-1 span-3">
            <label for="targetStatusID">Status</label>
        </div>
        <div class="span-3">
            <label for="targetBusinessUnitID">Business Unit</label>
        </div>
        <div class="span-3 prepend-1">
            <label for="targetStartDate">Start Date</label></div>
        <div class="span-3 prepend-2">
            <label for="targetEndDate">End Date</label>
        </div>
        <div class="prepend-1 span-3 last">
            &nbsp
        </div>        
        <div class="prepend-1 span-2">
            @Html.DropDownList("targetPriorityID", new SelectList(ViewBag.Priorities as System.Collections.IEnumerable, "ID", "Title"), "All")
        </div>
        <div class="prepend-1 span-3">
            @Html.DropDownList("targetStatusID", new SelectList(ViewBag.Statuses as System.Collections.IEnumerable, "ID", "Title"), "All")
        </div>
        <div class="span-3">
            @Html.DropDownList("targetBusinessUnitID", new SelectList(ViewBag.BusinessUnits as System.Collections.IEnumerable, "ID", "Title"), "All")
        </div>

        <div class="span-3 prepend-1">
            @Html.TextBox("targetStartDate", "")
        </div>
        <div class="span-3 prepend-2">
            @Html.TextBox("targetEndDate", "")
        </div>
        <div class="prepend-1 span-3 last">
            <input type="submit" value="Hide" />
        </div>
        <br />
        <br />
        <br />
    </div>


<div id="ticketsTable">
    @Html.Partial("_AllTickets", Model)
</div>

然后在一个单独的文件中对其进行 AJAX 化:

$(function() 
    $('form :input').change(function() 
        var form = $('form');
        $.ajax(
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            success: function(result) 
                $('#ticketsTable').html(result);
            
        );
    );
);

我建议您的另一个改进是使用视图模型并摆脱 ViewData 并使用强类型帮助器。

【讨论】:

达林,如果有机会,我会尝试这种方法,但是我以前的方法有什么根本错误吗?单独进行 AJAX 化有什么好处?另外,强类型助手是什么意思? 这在大多数情况下都有效,但我必须给所有的 DropDownLists 一个类并添加这部分 JS。 $(".ajaxForcePost").change(function () // $('form').submit(); );我不确定为什么您的解决方案没有像看起来应该的那样直接奏效。 即使这个解决方案在 100% 的情况下也不能正常工作。当然比上一个要多。【参考方案2】:

我可以看到的一个问题是 Razor 视图中的 AJAX 选项指定了 GET HTTP 方法,但控制器操作上的操作过滤器指定了 POST。

【讨论】:

【参考方案3】:

我想知道 Request.IsAjaxRequest() 是否导致了问题。我会考虑删除该代码并始终返回PartialView("__AllTickets", results);

【讨论】:

以上是关于Ajax.BeginForm(...) 并不总是有效,有时完全回发,使用 ASP.NET MVC的主要内容,如果未能解决你的问题,请参考以下文章

Ajax.BeginForm 验证模型

form表单和ajax表单提交(Html.BeginForm()Ajax.BeginForm())的差别

提交我的 Ajax.BeginForm 的其他 jQuery 事件

使用 JavaScript 提交 Ajax.BeginForm()

MVC小系列Html.BeginForm与Ajax.BeginForm

即使模型无效,ASP.NET MVC“Ajax.BeginForm”也会执行 OnSuccess