2017-02-19 63 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

似乎現在工作,謝謝! :) –