2017-02-19 5 views
0

jQuery/Ajaxで部分ビューをリフレッシュするための小さなデモ・アプリケーションをセットアップしました。私は、それがビュー自体からリフレッシュするものではないが、メインビューから部分ビューをリフレッシュする様々な例を見出した。セルフ・リフレッシュ・パーシャル・ビュー

これは私が使用しようとしたコードです:

メインビュー:

@model OrpheusTestWeb.Models.ViewModel 
@{ 
    ViewBag.Title = "Home Page"; 
} 
<h2>Guid1: @Model.GUID1</h2> 
<div id="PartialViewDIV"> 
    @Html.Partial("_PartialView", Model.GUID2) 
</div> 

部分図

@model string 

<h3>Guid2: @Model</h3> 

<input id="button" type="button" class="btn-danger" /> 

<script type="text/javascript"> 
    $("#button").on('click', function() { 
     $.ajax({ 
      url: "Partial/Index", 
      type: "get", 
      dataType: "html", 
      success: function (result) { 
       $("#PartialViewDIV").html(result); //the PartialViewDIV-tag is in the main view, how can i "redirect" it then? 
       console.log('success', data); 
      } 
     }); 
    } 
</script> 

と部分ビュー用コントローラ:

public class PartialController : Controller 
    { 
     public ActionResult Index() 
     { 
      return PartialView("_PartialView", Guid.NewGuid().ToString()); 
     } 
    } 

何が起こっているここで間違っている? ありがとうございます!

+1

あなたはここからいくつかのエラーまたは予期しない結果を得ている: は次のようなものですか?また、なぜあなたは部分的なビューでJavaScriptコードを入れているのですか?それはひどく悪いことです。通常、javascriptコードは別々のjavascriptファイルに属し、マークアップと混在することはありません。 –

+0

また、 ')'! – Shyju

+0

私はそれを同じファイルに入れて読みやすいようにしています。そのような生産には行かないでしょう:) –

答えて

0

なぜjsonを返さないのですか?

public class PartialController : Controller 
{ 
    [HttpGet] 
    public JsonResult Index() 
    { 
     return Json(new { _PartialView = Guid.NewGuid().ToString()},JsonRequestBehavior.AllowGet); 

    } 
} 

<script type="text/javascript"> 
$("#button").on('click', function() { 

    $.ajax({ 
     url: "Partial/Index", 
     type: "get", 
     dataType: "html", 
     success: function (result) { 
      var json = $.parseJSON(result); 
      $('#YourId').remove(); 
      $('#PartialViewDIV').append('<div id="YourId">' + json._PartialView + '</div>'); 
      //$("#PartialViewDIV").html(result); //the PartialViewDIV-tag is in the main view, how can i "redirect" it then? 
      // console.log('success', data); 
     } 
    }); 
}); 

+0

今、うまく動作しているようですね、ありがとう! :) –

関連する問題