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