【问题标题】:Reloading View does not update all of the controls on the form重新加载视图不会更新表单上的所有控件
【发布时间】:2013-10-04 05:02:31
【问题描述】:

我有一个包含@Html.DropDownListFor 的视图。当表单/视图加载时,如果其中一个模型属性具有值(IEnumerable),那么它将创建一堆具有相应数据的 div。如果该属性没有任何值(也称为 Count() == 0),那么它应该在表单上显示一个按钮(它将为该属性创建数据)。

因此,当用户从下拉列表中选择其中一个选项时,我会触发对填充当前表单/视图的完全相同的操作方法的 ajax 调用,但这一次,它在 id 字段中发送一个值。

我的操作方法中有一个断点,我验证它是否被命中,它具有正确的参数值并为传递给视图的模型创建正确的数据,但是......当模型发送到视图以重新填充,表单上的项目/控件都没有更改。我什至在 cshtml 文件中设置了断点,它也通过正确的数据进行处理。

所以,这是我的控制器:

public ActionResult Index(int? id)
        {
            var seasonId = id;

            if (seasonId == null)
            {
                var player = _playerRepository.Query().FirstOrDefault(p => p.PlayerId == _userIdentity.PlayerId);

                if (player.DefaultSeasonId != null)
                    seasonId = (int)player.DefaultSeasonId;
                else
                {
                    return View(new ScheduleModel
                    {
                        Player = player,
                        AvailableSeasons = _seasonRepository.Query().Select(s => s)
                    });
                }
            }

            return View(CreateScheduleModelForSeason((int)seasonId));
        }

这是我观点的开始:

@model LeagueManager.Models.ScheduleModel

@{
    ViewBag.Title = "Schedule(s)";
}

<div class="row">
    @Html.LabelFor(m => m.AvailableSeasons)
    @Html.DropDownListFor(m => m.SelectedSeasonId, new SelectList(Model.AvailableSeasons, "SeasonId", "SeasonName"), new { id = "seasonSelect" })
</div>

<form method="post" action="Schedule/GenerateSchedule">
    <h2>The Season's Schedules/Weeks and Matchups</h2>

    <div>
        <div>
            @if (Model.SchedulesAndMatches == null || (Model.SchedulesAndMatches != null && !Model.SchedulesAndMatches.Any()))
            {
                <input type="submit" class="btn btn-primary" value="Generate Schedule" />
            }
        </div>

这里是 ajax 调用:

@* Season Selector *@
$('select#seasonSelect').change(function () {
    var selectedSeasonId = $(this).val();

    $.ajax({
        url: '/Schedule/Index',
        data: { id: selectedSeasonId }
    });
});

再一次,所有实际代码都在工作,只是没有重新渲染视图...

示例:当调用 id = 1 的 ActionResult 方法时,它会加载整个计划。当通过下拉菜单切换到 id = 2 时(然后通过 ajax 再次调用),它保持相同的时间表。

另一方面:当调用 id = 2 的 ActionResult 方法时,它会加载单个按钮。通过下拉菜单切换到 id = 1 时,它会在模型​​中重新填充正确的数据,但视图/表单不会反映新信息。

请帮忙!

【问题讨论】:

  • 您能否进一步解释一下您究竟需要什么?当您从下拉列表中选择一个选项时,是否要更新下拉列表?

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


【解决方案1】:

当你使用 ajax 调用 action 时,你不能返回视图,你必须返回 json 数据。 因此,您的解决方案是删除 ajax 调用并使用您的帖子网址设置 window.location ..

@* Season Selector *@
$('select#seasonSelect').change(function () {
    var selectedSeasonId = $(this).val();

    window.location = '/Schedule/Index/' + selectedSeasonId;        

});

【讨论】:

  • 太棒了!我想说我忘记了,但这只是我写的第三个 ajax 调用。现在完美运行,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-21
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多