Ajax is not sending the data to the specified URL. Here is my controller:
#Controller
public class HomeController {
private List<User> userList = new ArrayList<User>();
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
public String showForm() {
return "AddUsers";
}
#RequestMapping(value = "User.htm", method = RequestMethod.POST)
public #ResponseBody
String addUser(#ModelAttribute(value = "user") User user,
BindingResult result) {
String returnText;
if (!result.hasErrors()) {
userList.add(user);
returnText = "User has been added to the list. Total number of users are"
+ userList.size();
} else {
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
#RequestMapping(value = "ShowUsers.htm")
public String showUsers(ModelMap model) {
model.addAttribute("Users", userList);
return "ShowUsers";
}
}
AddUser.jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
<script type="text/javascript">
function AjaxCall() {
alert('ready');
//get the form variables....
var name = $('#name').val();
var education = $('#education').val();
$.ajax({
type: "POST",
url: "AddUsers.htm",
data: " name=" + name + "&education=" + education,
success: function (response) {
$('#info').html(response);
$('#name').val('');
$('#education').val('');
},
error: function (e) {
alert('ERROR : ' + e);
}
});
}
</script>
<body>
<h1>Welcome to the AddUsers page. </h1>
<table>
<tr><td>Enter your name : </td><td> <input type = "text" id="name"></td></tr>
<tr><td>Educational qualification : </td><td> <input type = "text" id="education"></td></tr>
<tr><td colspan = "2"><input type="button" value="Add Users" onclick="AjaxCall()"></td></tr>
<tr><td colspan = "2"><div id ="info"></div></td></tr>
</table>
Show users
</body>
</html>
I have inserted an alert within the ajax which never comes up. So I believe there is something wrong with the ajax method.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have also created a domain class which would store the student information:
public class User {
private String name = null;
private String education = null;
public void SetName(String name) {
this.name = name;
}
public String GetName() {
return name;
}
public void SetEdu(String education) {
this.education = education;
}
public String GetEdu() {
return education;
}
}
There is also a warning:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with
URI [/sum/] in DispatcherServlet with name 'appServlet'>`
Dispatch servlet:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources
in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-
INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.faisal.sum" />
</beans:beans>
I corrected the upper case problem ($.ajax instead of $.Ajax). Thanks for pointing out.
Now I have a different error:
POST http://localhost:8080/sum/AddUsers.htm 405 (Method Not Allowed)
change url:"AddUsers.htm" to url: "${pageContext. request. contextPath}/AddUsers.htm" and try.
the url you are calling is this
type: "POST",
url: "AddUsers.htm",
Which is POST, the controller method is GET. Hecne the 405 error, method not supported.
You try to send POST request but mapped your method call with GET method
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
try to change RequestMethod.GET to POST
Related
I am a student who has just studied Ajax.
I have been constantly worried, but I have not been able to solve the problem.
So, I want to get some advice from you.
First, I will show the loginPage.jsp code and the MemberController.java code and the MemberService.java code.
It is loginPage.jsp code.
<%# page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/swiper.min.css">
<link rel="stylesheet" href="css/loginPage.css">
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js/swiper.jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<jsp:include page="header.jsp" />
<div class="loginPage_main">
<div class="pageName">
<img class="pageName_image" src="images/greeting_title.jpg">
<div class="pageName_explanation">
<p>로그인</p>
</div>
</div>
<div class="location">
</div>
<div class="loginForm_area">
<div class="hidden_area">
<div class="img_lock_area">
<img src="images/lock.png" class="img_lock">
</div>
<form action="loginOK.do" id="login_frm" name="frm" method="post" onsubmit="return checkValue()">
<div class="input_zone">
<div class="input_id">
<span> ID</span><input type="text" placeholder="아이디를 입력하세요" style="width:280px;margin-left: 10px;" name="id">
</div>
<div class="input_pw">
<span>PW</span><input type="password" placeholder="비밀번호를 입력하세요" style="width:280px;margin-left: 10px;" name="pw">
</div>
</div>
</form>
<div class="loginBtn" onclick="document.getElementById('login_frm').onsubmit();">
<div style="margin-top: 22px;">
<span class="loginOK">Login</span>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function checkValue()
{
var form = document.frm;
if(!form.id.value || !form.pw.value)
{
alert('아이디 혹은 비밀번호를 입력하세요.');
return false;
}
$.ajax
({
type: 'POST',
url: 'loginOK.do',
success: function()
{
alert('success');
},
error: function()
{
alert('error');
}
})
}
</script>
</body>
</html>
It is MemberController.java code.
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import service.MemberService;
#Controller
public class MemberController
{
#Autowired
public MemberService mService;
// 로그인
// 전송된 ID,PW값과 DB에 있는 ID,PW값 비교
// 맞으면 alert 창으로 " 로그인 성공 " 메세지 표출 + mainPage 이동
// 틀리다면 alert 창으로 " 로그인 실패 " 메세지 표출 + loginPage로 리다이렉트
#RequestMapping("loginOK.do")
public String login(String id, String pw,HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException
{
HashMap<String, Object> loginIdentify = mService.login(id,pw);
System.out.println("ID is : " + id + " / " + "PW is : " + pw);
if(loginIdentify != null)
{
System.out.println("loginIdentify is true : " + loginIdentify);
session.setAttribute("id", id);
session.setAttribute("pw", pw);
/*
- 오류로 인한 일시 보류 -
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.println("<script type='text/javascript'>");
writer.println("alert('로그인 성공!');");
writer.println("</script>");
writer.flush();
*/
}
else
{
System.out.println("loginIdentify is false : " + loginIdentify);
/*
- 오류로 인한 일시 보류 -
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.println("<script type='text/javascript'>");
writer.println("alert('로그인 실패!');");
writer.println("</script>");
writer.flush();
*/
return "redirect:move_loginPage.do";
}
return "redirect:main.do";
}
// 로그아웃
// 세션과 쿠키 제거 + mainPage로 리다이렉트
#RequestMapping("logout.do")
public String logout(HttpSession session, HttpServletResponse response)
{
session.removeAttribute("id");
Cookie cookie = new Cookie("id", null);
cookie.setMaxAge(0);
response.addCookie(cookie);
// 세션 삭제 확인
System.out.println("session is delete It's really? : " + session.getAttribute("id"));
return "redirect:main.do";
}
}
It is MemberService.java code.
package service;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import dao.IMemberDAO;
import model.Member;
#Service
public class MemberService
{
#Autowired
private IMemberDAO memberDao;
public HashMap<String, Object> login(String id,String pw)
{
HashMap<String, Object> result = memberDao.selectOne(id);
System.out.println(result);
if(result != null)
{
String opwd = (String) result.get("pw");
if(opwd.equals(pw))
{
return result;
}
else
{
return null;
}
}
else
{
return null;
}
}
}
When the form tag is executed, the ID value and PW value entered are compared with the ID value and PW value stored in the DB.
If the values match, go to the main page.
If the values do not match, you will not be able to log in without reloading the page! I want to print a message. How can I get it to work the way I want?
I do not know where to start.... I need your help vigorously.
Please advice to me your plan.
You're almost there.
Uncomment the code in MemberController.java that uses response to send data back to the client JavaScript. Something like—
PrintWriter writer = response.getWriter();
writer.println("login succeeded");
writer.flush();
—and similarly for the failure case.
Then, in loginPage.jsp, read the first argument in $.ajax's success function to get that same data back:
$.ajax
({
type: 'POST',
url: 'loginOK.do',
success: function(returnData)
{
console.log(returnData); // <---
},
error: function()
{
alert('error');
}
})
That way, the client will know whether the login succeeded or not, and you can call the appropriate JavaScript functions to open a different page, show an error, clear the password box, or whatever you want to do.
Tangential application security critiques:
I hope you're using HTTPS. If not, user credentials are easy for an attacker to steal.
It seems you are storing your users' passwords in plain text in your database. Consider salting them to protect them in case your database is compromised.
Hi i am trying to call servlet from jsp through ajax,and return two data from servlet. But facing some problem with result data.
both pono podt are combined together at output. how to split the same to get the correct data.
$(document).ready(function() {
$('#grn').blur(function() {
$.ajax({
url : 'callserv0',
type: 'POST',
data : {
grnno : $('#grn').val()
},
success : function(data) {
alert("new");
$('#pono').val(data);
$('#podt').val(data);
return false;
}
});
});
});
<script src="http://code.jquery.com/jquery-1.10.2.js"
type="text/javascript"></script>
<script src="js/app-ajax.js" type="text/javascript"></script>
</head>
<body>
<form>
Receipt number: <input type="text" id="grn" />
PO number: <input type="text" id="pono" />
PO Date : <input type="text" id="podt" />
<input type="button" id="find" value="Find" />
</form>
</body>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class callserv0 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//response.setContentType("text/html");
//PrintWriter out= response.getWriter();
//out.println("i am in callserv0");
String grn = request.getParameter("grnno");
String pono = grn;
String podt = "12/12/12";
response.setContentType("text/plain");
response.getWriter().write(pono);
response.getWriter().write(podt);
}
}
enter image description here
You can put a delimiter such as a comma(,) when you write the values to response.
Then use JavaScript method split()
.
var str = "123,2/21/2017";
var res = str.split(",");
console.log(res[0]);
console.log(res[1]);
I am testing some form submission code using spring MVC in the book "professional java for web applications". You can find the complete code in chapter 13 the spring-forms project
http://www.wrox.com/WileyCDA/WroxTitle/Professional-Java-for-Web-Applications.productCd-1118656466,descCd-DOWNLOAD.html
It works fine without the ajax part in the .jsp below. But when I add the jquery ajax part in the jsp, it does not work. The alert shows name to be undefined.
What did I do wrong?
Here is the code in the controller that binds the userForm object to the form in the .jsp below.
#RequestMapping(value = "user/add", method = RequestMethod.GET)
public String createUser(Map<String, Object> model)
{
model.put("userForm", new UserForm());
return "user/add";
}
#RequestMapping(value = "user/add", method = RequestMethod.POST)
public View createUser(#ModelAttribute("userForm") UserForm form)
{
User user = new User();
user.setUserId(this.getNextUserId());
user.setUsername(form.getUsername());
user.setName(form.getName());
this.userDatabase.put(user.getUserId(), user);
return new RedirectView("/user/list", true, false);
}
Here is the .jsp file
<%--#elvariable id="userForm" type="com.wrox.site.UserForm"--%>
<!DOCTYPE html>
<html>
<head>
<title>${title}</title>
<script src="http:////code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submitForm').submit(function(e) {
var frm = $('#submitForm');
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data : frm.serialize(), //JSON.stringify(data),
success : function(callback){
alert("Response: Name: "+callback.name);
$(this).html("Success!");
},
error : function(){
$(this).html("Error!");
}
});
});
});
</script>
</head>
<body>
<h1>${title}</h1>
<form:form method="post" modelAttribute="userForm" id = "submitForm">
<form:label path="username">Username</form:label><br />
<form:input path="username" /><br />
<br />
<form:label path="name">Name:</form:label><br />
<form:input path="name" /><br />
<br />
<input type="submit" value="Save" />
</form:form>
</body>
</html>
Here is the userForm
package com.wrox.site;
public class UserForm
{
private String username;
private String name;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
Here is the list.jsp
<%--#elvariable id="userList" type="java.util.Collection<com.wrox.site.User>"--%>
<!DOCTYPE html>
<html>
<head>
<title>User List</title>
</head>
<body>
<h2>Users</h2>
[new user]<br />
<br />
<c:forEach items="${userList}" var="user">
${user.name} (${user.username})
[edit]<br/>
</c:forEach>
</body>
</html>
Hi everyone I am trying to calla wcf service from a javascript function for some reason asp.net is not recognizing the namespace and give me an error on runtime, any help will be greatly appreciated following is code:
Default aspx page
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WeatherService.svc"/>
</Services>
</asp:ScriptManager>
Enter a zipcode:
<input id="zipCodeInput" type="text" />
<br/>
<input id="getForecastButton" type="button" value="Get Forecast" onclick="onGetForecast()"/>
<br/>
<div id="resultsDiv">
</div>
</form>
Javasript
<script language="javascript" type="text/javascript">
function onGetForecast() {
var zip = document.getElementById("zipCodeInput").value;
//alert(zip);
UltimateServices.GetForecast(zip, onGetForecastComplete, onGetForecastError, zip);
}
function onGetForecastComplete(result, userData) {
document.getElementById("resultsDiv").innerHTML = "Weather for " + userData + " is going to be " + result;
}
function onGetForecastError(err) {
alert("There was a error " + err.get_message());
}
</script>
WeatherService.cs file(codebehind)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
[ServiceContract(Namespace = "UltimateServices")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WeatherService
{
private static Random _rand = new Random();
[OperationContract]
public string GetForecast(string zipcode)
{
string forecast = "";
switch(_rand.Next(3))
{
case 0:
forecast = "Sunny and Warm";
break;
case 1:
forecast = "Chilly and overcast";
break;
case 2:
forecast = "Hot and humid";
break;
}
return forecast;
}
// Add more operations here and mark them with [OperationContract]
}
web.config file
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WeatherServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="WeatherService">
<endpoint address="" behaviorConfiguration="WeatherServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="WeatherService" />
</service>
</services>
</system.serviceModel>
here i call simple hello world from WCF using javascript
Service.cs
using System;
using System.Collections.Generic;
using System.Linq;`
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public string helloworld(string name)
{
name = "Hello " + name;
return name;
}
}
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="DefaultBehavior">
<endpoint address="" binding="webHttpBinding" contract="IService" name="RunningBarbus.Services.RunningBarbusService" behaviorConfiguration="AjaxBehavior">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding crossDomainScriptAccessEnabled="true">
<security mode="None"/>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="AjaxBehavior">
<!--<enableWebScript/>-->
<webHttp helpEnabled="true" automaticFormatSelectionEnabled="false" />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true" name="">
</standardEndpoint>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="access-control-allow-headers" value="content-type, Accept" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
javascript code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="jsonp.aspx.cs" Inherits="jsonp" %>
<!DOCTYPE html >
<html>
<head runat="server">
<title></title>
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var name="";
var Type;
var Url = "http://192.168.X.X/WCFjavascript/Service.svc/helloworld?name=world";
var Data;
var ContentType;
var DataType;
var ProcessData;
var method;
//Generic function to call WCF Service
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
// data: name, //Data sent to server
contentType: ContentType, // content type sent to server
//data: '[{"name":"' + name + '"}]',
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function (msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function ServiceFailed(xhr) {
alert(xhr.responseText);
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
function ServiceSucceeded(result) {
debugger;
if (DataType == "jsonp") {
alert(result);
resultObject = result.helloworld;
var string = result.name ;
alert(string);
}
}
function helloworld() {
debugger;
var uesrid = "";
Type = "GET";
// Url = "http://192.168.X.X/WCFjavascript/Service.svc/helloworld?'"+uesrid+'"';
Url = Url;
DataType = "jsonp"; ProcessData = false;
method = "helloworld";
CallService();
}
$(document).ready(
function () {
helloworld();
}
);
enter code here
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
You seem to lack the ScriptService/ScriptMethod attributes on your service/service methods.
I have a DataList and Update Panel in my page. After implementation, I checked that the response is talking very long time after using Update panels...Here is the study material. I have a Delete Command event in Datalist and works find in the above mentioned case. I was trying to implement Delete Command using Page Methods. Any Idea how to do that?
I basically want to find hidden controls in this event and have to delete the record in `database. Any help will be highly appreciated.
Rest Services
The full application can be downloaded from:
http://sdrv.ms/LJJz1K
This sample uses rest services in ASP.Net (the same concepts can be applied to a MVC application)
The clearer advantage when using rest services vs page methods, is testability.
I will guide you step by step to configure the service:
You need the following references:
System.Web.ServiceModel.dll
System.Web.ServiceModel.Activation.dll
System.Web.ServiceModel.Web.dll
Nuget packages:
jQuery
jQuery plugins:
jQuery Block UI (it’s available as a single script file)
Service info
[ServiceContract]
public interface IMyService
{
[OperationContract]
[WebInvoke(
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "/DeleteFromService",
Method = "DELETE")]
void Delete(int id);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{
public void Delete(int id)
{
// delete your product
// simulate a long process
Thread.Sleep(5000);
}
}
In Global.asax
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
RouteTable.Routes.Add(new ServiceRoute("",
new WebServiceHostFactory(),
typeof(MyService)));
}
In web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true"
automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
Register scripts (they can be registered in a master page)
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js" language="javascript" ></script>
<script language="javascript" type="text/javascript" src="Scripts/jquery.blockui.1.33.js"></script>
In a ASP.Net content page (in this sample, I am using a master page)
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<input type="button" value="Delete" id="myButton" />
</asp:Content>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" language="javascript">
function deleteFromService() {
if (!confirm("Are you sure you want to delete?")) {
return;
}
$.blockUI();
$.ajax({
cache: false,
type: "DELETE",
async: true,
url: "/DeleteFromService",
data: "3", // get your id to delete
contentType: "application/json",
dataType: "json",
success: function () {
$(document).ajaxStop($.unblockUI);
alert("done");
},
error: function (xhr) {
$(document).ajaxStop($.unblockUI);
alert(xhr.responseText);
}
});
}
jQuery().ready(function () {
$("#myButton").click(deleteFromService);
});
</script>
</asp:Content>
And that’s it, ajax commands the easy way =)