Ajax POST未在View

时间:2017-12-01 16:18:53

标签: javascript jquery asp.net ajax

我在刷新使用Ajax发布的数据时出现问题。 POST已成功执行,但VIEW上的数据不会使用新数据刷新。当我调试时,Ajax POST中的值成功传递给我的Search控制器。当控制器返回视图模型return View(model);时,我的VIEW不会刷新新数据。如何在我的视图中显示新数据?

的Ajax / jQuery的

$(document).ready(function () {
$("#typeId, #scorecardId, #dateId").on('change', function () {
        $.ajax({
            url: "/StaffChange/Search",
            type: "POST",
            dataType: "json",
            data: {
                typeSelected: $('#typeId').val(),
                scorecardSelected: $('#scorecardId').val(),
                effectiveDateSelected: $('#dateId').val()
            }
        })
});
});

查看

<table class="table table-condensed table-hover table-responsive table-striped">
<tr>
    <th>
        <a href="@Html.GetUrlAndRouteObject(Model.Sort, "change_date")">
            Change Date
            @Html.AddSortArrow(Model.Sort, "change_date")
        </a>
    </th>
    <th>
        @Html.EditorFor(model => model.effectiveDate, new { htmlAttributes = new { @class = "datepicker", @placeholder = "Effective Date", @id = "dateId" } })
    </th>
    <th>
        @Html.DropDownListFor(model => model.type, new SelectList(Model.type), "-Type-", new { @id = "typeId" })
    </th>
    <th>
        @Html.DropDownListFor(model => model.type, new SelectList(Model.scorecard), "-Scorecard-", new { @id = "scorecardId" })
    </th>
</tr>

@foreach (var item in Model.get_staff_changelog_results)
{
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Change_Date)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Effective_Date)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Type)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Scorecard)
            </td>
        </tr>
}

控制器

public ActionResult Search(string sort, string typeSelected, string scorecardSelected, DateTime? effectiveDateSelected)
    {
        //TO DO: Implement MVC way of permissions...
        if (System.Web.HttpContext.Current.Session["ConnectelligenceAdmin"].ToString() != "true")
        {
            return View("AccessDenied");
        }
        //Get sort order for Change Date using BLL
        var staffChangeSort = (String.IsNullOrEmpty(sort)) ? SortOptions.change_date_desc : (SortOptions)Enum.Parse(typeof(SortOptions), sort);

        //Execute sort order for Change Date using BLL
        var sortResults = _changeLogSort.SortStaffChangeLog(staffChangeSort,typeSelected, scorecardSelected, effectiveDateSelected);

        //Get list of dropdown results which is used for filtering
        var dropdownResults = _staffChangeFilter.StaffChangeFilter();

        var model = new Hierarchy_AdjustmentViewModel { get_staff_changelog_results = sortResults.get_staff_changelog_results, Sort = staffChangeSort, type = dropdownResults.type, scorecard = dropdownResults.scorecard};

        return View(model);
    }

2 个答案:

答案 0 :(得分:1)

因为您没有以任何方式响应AJAX调用。向the AJAX call添加.done()回调处理程序:

$.ajax({
    /*...*/
}).done(function (response) {
    // update the page in here
});

此时问题变成......您打算做什么样的更新?看起来您正在从控制器返回视图

return View(model);

因此,您在AJAX响应中获得的数据是一堆原始HTML。如果它是整页的子集(也就是说,没有额外的<head><body>等标签)那么你可以用现有的容器替换现有的容器元素。响应:

$('#someContainer').html(response);

然而,这往往有点草率,可能会导致其他问题。 (例如,替换连接到它们的处理程序或在其上初始化的插件的DOM元素,要求您重新思考如何处理某些事情。)相反,对于AJAX调用,返回JSON数据是常见的:

return Json(model);

这将返回仅数据而不是围绕此的所有HTML。这有用的原因有两个:

  1. 如果你只想做一些小而具体的事情,那么操作会更容易。
  2. 使用较少的网络带宽。
  3. 返回页面已经拥有的一堆HTML真是太愚蠢了。
  4. 使用该数据,您可以更新页面上的特定元素。例如,您可能想要更新输入的值:

    $('#someInput').val(response.SomeProperty);
    

    或显示元素的文本:

    $('#someElement').text(response.AnotherProperty);
    

    您如何处理响应以及您需要对页面进行“更新”的操作取决于您自己。关键是系统不会自动为您执行此操作。您需要处理AJAX响应并相应地编写逻辑。

答案 1 :(得分:1)

您需要使用从ajax调用中收到的响应。目前,您的Search方法正在返回查看结果。你可以做的是,如果从xhr调用调用该方法,你可以返回一个局部视图结果,该结果只有表行的标记(带有新的数据集)和你的ajax调用&#39; s {{ 1}} event,更新DOM(用这个新标记替换现有的表行)。

首先创建一个名为done的局部视图,并使用代码在那里呈现表行

_List.cshtml

您也可以在主视图中使用相同的局部视图来减少重复代码

现在更新您的操作方法,以便在从ajax代码

发出请求时返回此部分视图
@model Hierarchy_AdjustmentViewModel 
@if(Model.get_staff_changelog_results!=null)
{
    foreach (var item in Model.get_staff_changelog_results)
    {
        <tr>
            <td> @item.Change_Date </td>
            <td> @item.Effective_Date </td>
            <td> @item.Type </td>
            <td> @item.Scorecard </td>
        </tr>
    }
}

现在您要做的就是使用此响应来更新表。由于您要返回视图结果(HTML标记),因此无需将dataType指定为json。

public ActionResult Search(string sort, string typeSelected)
{
    // Your existing code to get data goes here
    var model = new Hierarchy_AdjustmentViewModel();
    mode.get_staff_changelog_results = sortResults.get_staff_changelog_result;
    if (Request.IsAjaxRequest())
    {
        return PartialView("_List", model);
    }
    return View(model);
}

另一个选择是将数据作为JSON数组返回,$("#typeId, #scorecardId, #dateId").on('change', function () { var $tbl = $(this).closest("table"); $tbl.find("tbody").find("tr:gt(0)").remove(); $.ajax({ url: "@Url.Action("Search","StaffChange")", type: "POST", data: { typeSelected: $('#typeId').val(), scorecardSelected: $('#scorecardId').val(), effectiveDateSelected: $('#dateId').val() } }).done(function(res) { $tbl.find("tbody").append(res); }).fail(function(x, a, e) { alert(e); }); }); 处理程序必须解析它(循环遍历它)并为每一行创建标记并附加到表(清除现有行之后)。 / p>

相关问题