ASP.NET MVC3 ajax局部视图刷新

时间:2012-05-12 14:24:10

标签: ajax asp.net-mvc-3 partial-views

我在asp.net mvc3中遇到了ajax更新div的问题。

我有一个内容视图

<div id="post_comments">
   @{Html.RenderPartial("_RefreshComments", Model);}
 </div>
<div id="commentForm">
@using (Ajax.BeginForm("Details", new { id = Model.Post.PostId }, new AjaxOptions
           {
              HttpMethod = "POST",
              InsertionMode = InsertionMode.InsertAfter, 
              UpdateTargetId = "post_comments"
            }
          ))
{
// form content goes here
<p id="buttons">
    <input type="submit" value="@Strings.Save" />
</p>
}

这是我的部分观点

@model Project.Models.Posts.PostDetailsViewModel   

@{ 
    foreach (var c in Model.ApprovedComments)
    { 
        @Html.DisplayFor(x => c)        
    } 
}

我有一个控制器

public ActionResult Details(int id, FormCollection form )
{
    var model = new PostDetailsViewModel(UnitOfWork, id);
    return PartialView("_RefreshComments", model);

}

我的布局cshtml中包含以下脚本

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

以及

  <appSettings>
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>  

它确实有效,我可以添加注释,但控制器只返回未包含在布局中的PartialView。我被发现ASP.net MVC3 - Razor Views and PartialViews with Ajax Postbacks但是没有任何东西可以帮助我。

有没有人有任何想法?

2 个答案:

答案 0 :(得分:2)

我会使用jquery ajax来调用该操作,然后从控制器返回局部视图。然后使用jquery将返回的html重新加载到容器中。

首先,添加一个刷新按钮或者你可以触发ajax事件的东西...然后执行以下javascript。

做这样的事情:

<div id="post_comments">     
  @{Html.RenderPartial("_RefreshComments", Model);}    
</div>
<div id="commentForm">
  @using (Ajax.BeginForm("Details", new { id = Model.Post.PostId }, new AjaxOptions    
  {
     HttpMethod = "POST",
     InsertionMode = InsertionMode.InsertAfter, 
     UpdateTargetId = "post_comments"
  }
))
{
// form content goes here
<p id="buttons">
  <input type="submit" value="@Strings.Save" />
  <input type="button" id="refreshButton" value="Refresh" />"
</p>
}





$('#refreshButton').click(function(){
   $.ajax({
      url: 'controller/Details.aspx',
      datatype: 'html',
      success: function(data) {
         $('#post_comments').empty().html(data);
      }
   }); 
});

显然,网址必须是您行动的途径。除此之外,这应该适合你。

答案 1 :(得分:0)

用法:

    function onUploadComplete()
    {
        @Ajax.Update("targetId", helper => helper.Action("ActionName"))
    }

代码:

    /// <summary>
    /// I'd rather stab myself in the eye with a fork than bothering with php ever again and living without extension methods
    /// </summary>
    /// <param name="helper">makes sense to make it available here. who likes dozens of new helper classes</param>
    /// <param name="updateTargetId">simple enough</param>
    /// <param name="actionUrlFactory">resharper will show if we're messing stuff up. hurray.</param>
    /// <param name="isAsync">speaks for itself</param>
    /// <param name="options">might as well reuse that one for callbacks</param>
    /// <returns>generated code with compile time checks</returns>
    public static IHtmlString Update(this AjaxHelper helper, string updateTargetId, Func<UrlHelper, string> actionUrlFactory, bool isAsync = true, AjaxOptions options = null)
    {
        var requestUrl = actionUrlFactory(new UrlHelper(helper.ViewContext.RequestContext));
        if (options == null)
        {
            options = new AjaxOptions()
            {
                AllowCache = false,
                HttpMethod = "GET"
            };
        }

        string cache = options.AllowCache ? "true" : "false";
        string success = options.OnSuccess.Length > 0 ? ".done(" + options.OnSuccess + ")" : "";
        string fail = options.OnFailure.Length > 0 ? ".fail(" + options.OnFailure + ")" : "";
        string always = options.OnComplete.Length > 0 ? ".always(" + options.OnComplete + ")" : "";
        string isAsyncString = isAsync ? "true" : "false";

        // of course you can go way further here, but this is good enough for me. just sharing since i didn't find a nice solution here that doesnt involve writing js manually every time.
        string js = string.Format(@"
            $.ajax({{
                cache : {7},
                async : {6},
                url : '{0}',
                type : '{1}'
            }})
            .done(function(data){{
                $('#{5}').html(data);
            }});
            {2}
            {3}
            {4}
        ", requestUrl, options.HttpMethod, success, fail, always, updateTargetId, isAsyncString, cache);

        return new HtmlString(js);
    }