Wednesday, February 10, 2010

Calling Controller Page Methods using JavaScript in MVC

First Check whether the Browser supports the Ajax or Not.
================

function GetXmlHttpObject() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
====
Then Write The following Code.
=============
function ConfirmMsg() {
if (confirm("put the confirmation message, clicking cancel of this will not cause a post back")) {
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = "/Folder or ControllerName/MethodName";
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4){
document.getElementById('objDiv').value = xmlHttp.responseText;
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return false;
}
}
=====
Enjoy...