2012-03-14 60 views
0

我正在嘗試使用ajax刷新部分新數據。 我用在JavaScript這樣的功能:如何使用ajax post使用新數據渲染局部視圖?

function replace{ 
    $.ajax({ 
     url: '@Url.Action("DoThing", "Controller"), 
     type: "POST", 
     datatype: "actionresult", 
     async: false, 
     data: {itemCode: $("#ComboBox-input").val(), unitCode: @(Model.UnitCode)} 
    }); 
} 

而控制器動作:在調試期間

Public ActionResult DoThing(int itemCode, int unitCode) 
{ 
    var aThing = new ExModel 
        { 
         ItemCode = itemCode, 
         UnitCode = unitCode 
        } 
    return PartialView("_InPartial", aThing); 
} 

現在我得到與我發送的數據, 控制器動作,但我不知道如何用返回的數據渲染局部視圖。

回答

2

首先,你的部分必須是在其中您可以參考JS,像這樣的元素:

<div id="myPartialDiv"><!-- here your partial --></div> 

然後,刪除數據類型(非必要),並添加成功方法,它將把服務器響應(渲染的部分)在div:

function replace{ 
    $.ajax({ 
     url: '@Url.Action("DoThing", "Controller")', 
     type: "POST", 
     async: false, 
     data: {itemCode: $("#ComboBox-input").val(), unitCode: @(Model.UnitCode)}, 
     success: function(response){ 
      $('#myPartialDiv').html(response); 
     } 
    }); 
} 

通常你不必這樣做你自己,我覺得你有你自己的理由。 但通常您應該使用Ajax.ActionLinkAjaxOptions,您將UpdateTargetId設置爲myPartialDiv。