2012-05-12 3 views
2

asp.net mvc3에서 div의 ajax 업데이트에 문제가 있습니다.ASP.NET MVC3 ajax 부분 뷰 새로 고침

나는이 내 부분보기

@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

에 포함 된 컨트롤러에게이 내용

<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> 
} 

와보기를

<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를 찾았지만 거기에서 아무 것도 나를 도왔다.

누구에게 아이디어가 있습니까?

+0

당신이 AJAX 요청을 볼 수있는 브라우저에서 자바 스크립트 디버깅 도구에서 트리거되는? 자바 스크립트 오류가있을 수 있습니까? 'jquery.unobtrusive-ajax.min.js' 스크립트가 지정된 위치에 있는지 확인 했습니까? 'jquery'도 참조 했습니까? –

+0

아니요, Request.IsAjaxRequest()는 항상 false를 반환합니다. 예. 모든 페이지에서 스크립트를 사용할 수 있습니다. 예 jquery는 작동하지만 왜 false를 반환하는지 모르겠습니다. 이것에 대한 몇 가지 주제를 읽었습니다 ... 그러나 .... – TheKnyazz

답변

2

jquery ajax를 사용하여 동작을 호출 한 다음 컨트롤러에서 부분 뷰를 반환합니다. 그런 다음 jquery를 사용하여 컨테이너에 반환 된 HTML을 다시로드하십시오.

먼저 새로 고침 버튼을 추가하거나 ajax 이벤트를 트리거 할 수있는 항목을 추가 한 다음 아래 자바 스크립트를 수행하십시오. 이 같은

어떻게 좀은 :

<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); 
     } 
    }); 
}); 

물론, URL은 행동에 대한 경로 할 필요가있다. 그것 이외에, 이것은 당신을 위해 잘 작동해야합니다.

+0

거의 작동하지만, @ Url.Action()을 통해 매개 변수를 전달할 때 몇 가지 문제가 있습니다. 나는 formcollection과 Id를 전달해야합니다. – TheKnyazz

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); 
    } 
관련 문제