MVC Action / RenderAction,ajax post和Partial Views的奇怪行为

时间:2013-08-02 00:14:45

标签: c# asp.net-mvc jquery html-helper asp.net-mvc-partialview

所以设计理想是在这个MVC应用程序中有一个页面带有几个不同的“小部件”。每个“小部件”都应该能够将信息提交回自身并仅重新加载。简单的Web表单,而不是MVC似乎

首先,我们有主页控制器,没什么特别的

public ActionResult Index()
{
    return View();
}

接下来,我们有主页面View。请注意,我已尝试过Action和RenderAction,并且行为没有变化

@Html.Action("Index", "Monitor", new { area = "Statistics" }); 

<div id="messages">
    @Html.Action("Index", "Messages", new { area = "Data"});
</div>

@section Script {
    <script src="@Url.Content("~/Scripts/jquery-1.9.1.min.js")" type="text/javascript"></script>
<script type="text/javascript">
    $('#filter').click(function () {
        $.ajax({
            method: 'POST',
            url: '@Url.Action("Index", "Messages", new { area = "Data"})',
            success: function(data){
                $('#messages').html(data);
            }
        });
        return false;
    });
</script>

消息控制器中的Index ActionResult:

public ActionResult Index()
{
    var model = GetMessages();
    return PartialView(model);
}

为了简洁起见,将跳过整个监控索引视图,并仅提供消息索引视图的简短版本

@using (Html.BeginForm("Index", "Messages", FormMethod.Post))
{
    //Some fields to limit results are here, with style classes
    <button type="submit" id="filter">Filter</button>
}

@foreach(var item in Model)
{
    //Display results 
}

加载主页后,一切看起来都不错。将显示限制结果的字段以及消息。我可以在字段中输入内容,单击Filter,然后返回主页面,但是! ...这些字段丢失了它们的样式类,并且消息未经过滤。

奇怪,但更奇怪的是,如果我再次在字段中输入信息并单击过滤器,这次我没有被带到主页面,但只获得显示的消息索引的部分视图,并且不过滤消息。

我不能说过滤不起作用与此问题有关,但点击过滤器的不一致行为是困扰我的部分。有人想在这里指出我做错了吗?

1 个答案:

答案 0 :(得分:0)

您可能应该在小部件中使用Ajax.BeginForm而不是Html.BeginForm。这将让小工具管理自己的帖子:

<div id="messages">
  @using (Ajax.BeginForm("Index", "Messages", new AjaxOptions { UpdateTargetId = "messages" }))
  {
    // fields content
  }
  // other widget content
</div>

您所看到的“奇怪”行为正在发生,因为在页面加载时,#filter按钮的提交事件正在使用jQuery被劫持,但在第一次替换窗口小部件内容后,#filter提交事件不再被劫持,因此当您单击它时,整个页面都会被提交。如果您不想使用Ajax.BeginForm,则需要使用$.on而不是$.click来注册事件,因为它将处理事件后匹配元素的事件注册脚本已经运行。