Create wcf service to call by jquery ajax json

In this post we will see how to create wcf service in C# that we can call through jquery ajax and json. The namespaces we need in wcf service are System.ServiceModel, System.ServiceModel.Web and System.ServiceModel.Activation.

create wcf service to be called by jquery ajax json

Example- WCF service to call by jquery ajax json

using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.Web;

namespace aspnetcontrol
{
  [ServiceContract(Namespace = "")]
  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class Service1 
  {
    [WebGet()]
    [OperationContract]
    public string GetMessage(string message)
    {
      return "WCF" + message;
    }
  }
}

Note: In above code important attributes are [ServiceContract(Namespace = "")], [OperationContract] and [WebGet()]. ServiceContract specifies that class defines service contract in application.
OperationContract specifies that a method defines and operation that is part of web service contract.
WebGet indicates service operation is logically a retrieval operation. In this way we can create wcf service to be called using jquery ajax json. In order to make service accessible we need to configure wcf service in web.config.

jQuery Ajax call to WCF service

In jQuery we can perform an asynchronous HTTP (Ajax) request. In this post we will see simple example of how jquery Ajax call to WCF service works. We can call wcf service using jquery ajax and json.

use jquery ajax to call wcf service
We can use $.ajax to call the wcf service like:
 var dto = { message: $("#messageinput").val() };
        $.ajax({
          type: 'GET',
          url: '',
          data: dto,
          contentType: "application/json; charset=utf-8"
        })
        .success(function (response) {
          alert(response.d);
        })
        .error(function (response) {
          alert("ERROR"+response.d);
        });


Here in above code snippet we have set various parameters for jquery ajax call like: type: 'GET' - means request is of type GET and not POST
url: '', here we have mentioned the url of wcf service, where Service1.svc is wcf service name, get-json is address set in the web.config wcf service and GetMessage is actual method in wcf service.
data: dto is the parameter data that we need to pass to wcf service method.

Example jquery ajax call to wcf service

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <title>Jquery ajax json call to wcf service</title>
  <script type="text/javascript">
   $(document).ready(function () {
      $("#btnClick").click(function () {
        var dto = { message: $("#messageinput").val() };
        $.ajax({
          type: 'GET',
          url: '<%= ResolveUrl("~/Service1.svc/get-json/GetMessage") %>',
          data: dto,
          contentType: "application/json; charset=utf-8"
        })
        .success(function (response) {
          alert(response.d);
        })
        .error(function (response) {
          alert("ERROR"+response.d);
        });
      });
    });
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input type="text" id="messageinput" />
    <asp:Button ID="btnClick" runat="server" Text="Button" />
  </div>
  </form>
</body>
</html>

In above example we can type some message in textbox and pass message to wcf service using jquery ajax call and get it in respose back.

Note: To run above example we need to create wcf service and configure wcf service endpoint in web.config file properly

jquery set dropdownlist exact text

We have seen how to set selected option in dropdown list by text here set dropdownlist selected option by text. In that example we used :contains selector that will look for the text and the set text in dropdownlist as selected.

dropdownlist set exact selected text
But if dropdownlist have items with same texts instance then :contains selector will get all the items with matched text. This might show last matched item selected in dropdownlist. In this case we need to use alternate way to get exact text in dropdownlist and then set it selected.

Example to set selected option in dropdown by exact text [jquery]


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <title>set dropdown value</title>
  <script type="text/javascript">
    $(document).ready(function () {
      $("#go").click(function () {
        var inputText = $("#inputText").val();
        $("#numbers").each(function () {
          $('option', this).each(function () {
            if ($.trim($(this).text().toLowerCase()) == $.trim(inputText.toLowerCase())) {
              $(this).attr('selected', 'selected');
            };
          });
         });
       });
    });
 </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <label>Enter value from dropdown</label>
    <input type="text" id="inputText" />
    <asp:DropDownList ID="numbers" runat="server">
      <asp:ListItem Text="This is one" Value="1"></asp:ListItem>
      <asp:ListItem Text="This is one?" Value="2"></asp:ListItem>
      <asp:ListItem Text="This is three" Value="3"></asp:ListItem>
    </asp:DropDownList>
  </div>
  <input type="button" id="go" value="Go" />
  </form>
</body>
</html>

Summary: So by using :contains it might not work for multiple items with istance of same text. But we can iterate through dropdown items and then by matching exact text we can set dropdown list text selected.

Dropdownlist set selected value

In this post we will see in jquery how toset dropdown list value or selected option by it's value. For that we simply need to get object of dropdown list in jquery and then we can set selected option by using val(). of dropdownlist.

jquery dropdownlist set selected value

Example: set dropdown list selected option by value [jQuery]

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>jQuery set dropdown list selected option by value</title>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#go").click(function () {
          var inputText = $("#inputText").val();
          $("#numbers").val(inputText);
        });
      });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <label>Enter value between 1-3</label>
      <input type="text" id="inputText"/>
    <asp:DropDownList ID="numbers" runat="server">
    <asp:ListItem Text="1" Value="1"></asp:ListItem>
    <asp:ListItem Text="2" Value="2"></asp:ListItem>
    <asp:ListItem Text="3" Value="3"></asp:ListItem>
    </asp:DropDownList>
    </div>
    <input type="button" id="go" value="Go" />
    </form>
</body>
</html>

Summary: So in short we can use jquery to set dropdownlist item value like $("#numbers").val(inputText);. we can also set dropdown list selected option by using text like Set selected value by text.

Assign value to span - jquery

In this post we will see set a value to span tag using JQuer. To change value of span we can access span tag directly like $('span') and then using its .html() method we can assign some text to it.

assign value to span jquery

Example to assign text to span [jQuery]

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>Assign value to span in jQuery</title>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#submitbtn").click(function () {
          var inputValue = $("#inputText").val();
          $('span').html(inputValue);
        });
      });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <label>Type some text here to assign to span</label>
        <input type="text" id="inputText"/>
        <input type="button" id="submitbtn" value="Submit" /><br/>
        <span style="width:500px;height:120px; background-color:thistle">&nbsp;</span>
    </div>
    </form>
</body>
</html>

Summary:So to replace span tag text we get the object of span tag like $('span') and using .html() we can change value of span.

Set selected option by text of dropdownlist


In this post we will see how to set selected option by text to dropdownlist. In web application we need to set dropdownlist value at client side. By using option property of dropdown list we will check if dropdown contains text that we want to set And after that using selected attribute we will set it true so that it will show the option selected that we have set using text.
set selected option in dropdownlist using jquery

Sample to set selected option by text to dropdownlist[jQuery]


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>Set dropdownlist selected option by text</title>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#go").click(function () {
         var inputText = $("#inputText").val();
          $("#numbers option:contains(" + inputText + ")").attr('selected', 'selected'); 
        });
      });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <label>Enter value between 1-3</label>
      <input type="text" id="inputText"/>
    <asp:DropDownList ID="numbers" runat="server">
    <asp:ListItem Text="1" Value="1"></asp:ListItem>
    <asp:ListItem Text="2" Value="2"></asp:ListItem>
    <asp:ListItem Text="3" Value="3"></asp:ListItem>
    </asp:DropDownList>
    </div>
    <input type="button" id="go" value="Go" />
    </form>
</body>
</html>


Summary:By using $("#numbers option:contains(" + inputText + ")").attr('selected', 'selected'); we have dynamically set the selected option of a drop-down list using JQuery.We can set selected option of dropdown list by it's value likeset selected option of dropdown box by value

Set value to textarea - jQuery

In this post we will see how to set value to textarea in jQuery. To assign value to textarea in jquery we can use .val() method of textarea. In example we will take value from input testbox and assign it to textarea.

set value to textarea in jquery

Example to set value to textarea [jQuery]

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/i18n/jquery-ui-i18n.min.js"></script>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" />
    <title>Set textarea value in jQuery</title>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#submitbtn").click(function () {
          var inputVal = $("#inputText").val();
          $("#txtMessage").val(inputVal);
        });
      });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <label>Type Text here</label>
        <input type="text" id="inputText" /><br/>
        <textarea cols="50" rows="5" id="txtMessage"></textarea><br/>
        <input type="button" id="submitbtn" value="Submit" />
    </div>
    </form>
</body>
</html>

Regex for email validation JavaScript

In this post we will see how to validate email format in Javascript using regular expression. We can use regular expression (/^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$/i) to validate the email address in javascript.

Regular expression to validate email format in JavaScript

Example of email validation using regex in javascript

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Regex to validate email format in JavaScript</title>
  <script language="javascript" type="text/javascript">
    function Validate() {
      var emailRegex = new RegExp(/^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$/i);
      var emailAddress = document.getElementById("<%= txtemail.ClientID %>").value;
      var valid = emailRegex.test(emailAddress);
      if (!valid) {
        alert("Invalid e-mail address");
        return false;
      } else
        return true;
    }
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:TextBox runat="server" ID="txtemail"></asp:TextBox>
    <asp:Button runat="server" ID="Send" OnClientClick="return Validate();" Text="Send" />
  </div>
  </form>
</body>
</html>

Validate email format - RegularExpressionValidator

In asp.net in order to validate email address format we can use RegularExpressionValidator. We will see how to use RegularExpressionValidator to validate the email address format.For that we need to specify the Regular expression or regex in ValidationExpression property of the RegularExpressionValidator. Also we need to specify few other properties like ErrorMessage to display error message when email address is invalid. also we need to specify ControlToValidate property where we have to give textbox controls name in which user enters email address.

Validate email address using regular expression validator

Example to validate email address using RegularExpressionValidator

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Validate email format </title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:TextBox ID="txtEmail" runat="server" />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
    <asp:RegularExpressionValidator ID="validateEmail" runat="server" ErrorMessage="Invalid email."
      ControlToValidate="txtEmail" ValidationExpression="^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" />
  </div>
  </form>
</body>


Also we need to check !Page.IsValid in event hadler of control like button or link...etc like
  protected void btnSubmit_Click(object sender, EventArgs e)
    {
      if (!Page.IsValid)
        return;
    }

Remove special characters - jQuery

In this post we will see how to remove special characters like !,@,$,*,^ ...etc. from the string. For that we need to specify the special characters in regular expressions. Then by passing specified regular expression to .replace method in jquery and replace it with '' blank.

remove special characters from string in jquery

Example to remove special characters from string - jquery

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>Remove special character fromstring</title>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#Send").click(function () {
                var originalstring = $("#txtinput").val();
                var filteredString = originalstring.toLowerCase().replace( /[\*\^\'\!\@\$]/g , '');
                alert(filteredString);
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox runat="server" ID="txtinput"></asp:TextBox>
    <asp:Button runat="server" ID="Send" Text="Send" />
    </div>
    </form>
</body>
</html>


We can use regular expressions to define the special character set that we need to remove from string. so if you want to remove * from the string the regular expression will be /[\*]/g. Now if you want to remove ! also the add ! to regular expression like /[\*\!]/g and so on.