Call controller action from jquery ajax and capture the result

Ankaprasad
Posted by Ankaprasad under ASP.NET MVC category on | Points: 40 | Views : 715
Controller code

 [HttpGet]
public ActionResult SearchResults(string phone)
{

string recordUrl = "";
string strurl = String.Format("http://localhost:60045/api/Search/{0}", phone);
WebRequest requestobj = WebRequest.Create(strurl);

requestobj.Method = "GET";
requestobj.ContentType = "application/json";
{
using (WebResponse response = (HttpWebResponse)requestobj.GetResponse())
{
string strheader = string.Empty;
using (var sr = new StreamReader(response.GetResponseStream()))
{
recordUrl = sr.ReadToEnd();
}
}
}
return Json(recordUrl, JsonRequestBehavior.AllowGet);
}



Jquery in View


$("#btnSearch").on("click", function () {

var $this = $(this);
$this.button('loading');
var searchText = $("#SearchText").val();

if (searchText == '' || searchText == null || searchText == 'undefined') {
alert('Mobile number should not be empty');
$this.button('reset');
return;
}
var serviceURL = '/Search/SearchResults?phone=' + searchText;

$.ajax({
type: "GET",
url: serviceURL,
//data: param = searchText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
}).done(function () {
$this.button('reset');
});;

});

function successFunc(url, status) {
var a = url.replace(/\"/g, "");
window.open(a, '_blank');

}

function errorFunc() {
alert('error');
}

Comments or Responses

Login to post response