基本的なパターンは、コントローラーで PartialView の結果を作成し、その結果を使用してページ上のコンテナーの innerHTML を更新することです。
HTML
<input type="button" onclick="UpdateMyContainer();" value="Update" />
<div id="MyContainer">
@Html.Partial( "_MyPartialView", Model )
</div>
JavaScript
JQuery を必要としない Ajax メソッドの作成については、初心者向けの jQuery を使用しない Ajax に従ってください。基本的に:
function UpdateMyContainer() {
var xmlHttp = createXMLHttp();
// set your controller URL here:
xmlHttp.open('get', 'Url/To/SomeMethodInController', true);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
// Set the Id of the container to update here:
document.getElementById('MyContainer').innerHTML = xmlHttp.responseText;
} else {
alert('Error: ' + xmlHttp.responseText);
}
} else {
//still loading
}
};
}
上記の JS をさらにリファクタリングして、更新する要素の URL と ID を受け取ることができます。
コントローラ
[HttpPost]
public PartialViewResult SomeMethodInController()
{
var model = MethodToRetreiveModel();
return PartialView( "_MyPartialView", model );
}