How to call Webservice(.ASMX) from MVC View using Jquery

How to call a webservice from MVC View, There is only 1 condition to call .asmx file from in a mvc view.
  1. It should be within the same project.
How to call:
  1. Create your asmx file in root folder or Inside any folder.
  2. Set in your route.Confige file-routes.IgnoreRoute("{*x}", new { x = @".*\.asmx(/.*)?" });
  3. Add [ScriptMethod] attribute to your web method along with [WebMethod].
  4. Add namespace "using System.Web.Script.Services" to your web services that will call [ScriptMethod].
From wher to call:
  1. From your MVC View using jquery, like simple call.
HTML:   
  1. <p><button id="btnclickme">clickme</button></p>  
Script:
  1. <script src="~/Scripts/jquery-1.10.2.js"></script>  
  2. <script type="text/javascript">  
  3.    $('#btnclickme').click(function () {  
  4.       $.ajax({  
  5.          type: "POST",  
  6.             url: "/WebServices/MyService1.asmx/HelloWorld",  
  7.          contentType: "application/json; charset=utf-8",  
  8.          dataType: "json",  
  9.          success: function (msg) {  
  10.          alert('success');  
  11.             },  
  12.          error: function (e) {  
  13.          alert('error: ' + e.msg);  
  14.          }  
  15.          })  
  16.       })  
  17.    </script>  
WebService:        
  1. public class MyService1 : System.Web.Services.WebService  
  2. {  
  3. [WebMethod]  
  4. [ScriptMethod]  
  5. public string HelloWorld()  
  6. {  
  7.    return "Hello World";  
  8.   }  
  9. }  
Description:

In above code I created a simple mvc Controller named Home which has an Action-Index, in Index.cshtml I have a button which calls my web service.

Note:

In this code my webservice "MyService1.asmx" file inside a root folder named as WebServices, I used at calling time from Jquery.
Ebook Download
View all
Learn
View all