Web
Analytics
jquery post example using asp.net web api 2 with cross origin | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

  1. Install Microsoft.AspNet.WebApi.Cors using nuget package manager console
  2. Make Changes at webapi.config
  3. var enableCorsAttribute = new EnableCorsAttribute(“*”,
  4. “*”,
    “*”);
    config.EnableCors(enableCorsAttribute);
  5. Create web api 2 controller with entity framework, please select appropriate model and context class
  6.  [EnableCors(origins: "http://localhost:52146", headers: "*", methods: "*")]

    7. Client Program which making POST request.




    @{
        ViewBag.Title = "Index";
        Layout = null;
    }
    
    <h2>Index</h2>
    <script src="~/Scripts/jquery-3.3.1.js"></script>
    <script>
        
    $(document).ready(function () {
    $("#btn1").click(function () {
    
    $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    headers: {
        "Content-Type": "application/json"
    
    },
    url: "http://localhost:51747/api/Employees/",
    data: "{'EmpName':'" + $("#EmpName").val() + "','Salary':" + $("#Salary").val() + ",'Address':'"+$("#Address").val()+"'}",
    dataType: "json",
    success: function (data) {
    var obj = data.d;
        //alert(data);
    if(data!=null)
    {
        alert('Congrats Data is submitted');
    }
    
    },
    error: function (result) {
    alert("Error");
    }
    });
    })
    })
    
    </script>
    
    <input type="text" id="EmpName" name="EmpName" value="" /><br />
    <input type="text" id="Salary" name="Salary" value="" /><br />
    <input type="text" id="Address" name="Address" value="" /><br />
    <input type="button" id="btn1" name="btn1" value="SignIn" />
    -
    
    

     

    Due to some IIS permission issue , PUT and DELETE verbs does’t work, In that case don’t forget to update web.config file

     
      
     
     
              
        
    
    

    Download Source Code