inforakesha

A fine WordPress.com site


Leave a comment

JQGRID BASIC

  1. To Select multiple rowsvar

    selRowIds = myGrid.jqGrid ('getGridParam', 'selarrrow');

  2. To Select single row

    var selRowId = myGrid.jqGrid ('getGridParam', 'selrow');

   3.To get selected row
$(‘#plant-to-godown tr:eq(‘+1+’)’);
where 1 is rowid.

 4.To Get Row data by passing rowid
$(‘#plant-to-godown’).jqGrid(‘getRowData’, 1)


Leave a comment

Jquery Making call only first time OnClick event

 

 

change

$("a.test").click(function() {

to

$("a.test").live('click', function() {

The reason why only the first element is working is because at the time the click event is attached, there is only one <a> element on the page. You need to explicitly add the click event handler to every anchor that is created, or use live events instead. Read more about live event handlers.


Leave a comment

Get Form’s Post Values in ASP.NET MVC with FormCollection

20MAR

In addition to this post, you can also get the form’s post values with System.Web.Mvc.FormCollection in ASP.NET MVC 2 or MVC 3.

Here are my controllers, one for display the page, one for process page post back:

1
2
3
4
public ActionResult SubmitFormWithFormCollection()
{
    return View();
}
1
2
3
4
5
6
7
8
9
10
[HttpPost]
public ActionResult SubmitFormWithFormCollection(FormCollection formCollection)
{
    foreach (string _formData in formCollection)
    {
        ViewData[_formData] = formCollection[_formData];
    }
    return View();
}

Here’s my code in Razor view engine:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@{
    ViewBag.Title = "Submit Form With FormCollection";
}
<h2>Submit Form with FormCollection</h2>
@using (Html.BeginForm())
{
    <div>
        You have submitted:<br />
        Firstname: @ViewData["firstname"]<br />
        Lastname: @ViewData["lastname"]<br />
        Email: @ViewData["email"]<br />
    </div>
    <br />
    <label for="firstname">Firstname:</label>
    <input type="text" name="firstname" />
    <br />
    <label for="lastname">Lastname:</label>
    <input type="text" name="lastname" />
    <br />
    <label for="email">Email:</label>
    <input type="text" name="email" />
    <br />
    <br />
    <input type="submit" name="submit" />
}

When the view is loaded, it looks like:

And when it posted:

FormCollection (System.Web.Mvc.FormCollection) class contains key / value pairs from all the fields in the form submitted.

The FormCollection’s key is the ‘name’ attribute of the HTML control field in the form while the value is the user’s input to that field. So, to get value of the ‘firstname’ field, I can do:

1
2
3
4
5
6
7
[HttpPost]
public ActionResult SubmitFormWithFormCollection(FormCollection formCollection)
{
    ViewData["firstname"] = formCollection["fistname"];
    return View();
}


Leave a comment

Uploading image in file in MVC

STEP1 In View

 

<p>
@using(Html.BeginForm("Index","Image",FormMethod.Post,new{enctype="multipart/form-data"}))
{
<labelfor="file">UploadImage:</label>
<inputtype="file"name="file12"id="file"onclick="validate()"/>
<inputtype="submit"value="UploadImage"/>

<imgsrc=""alt="image"id="img1"width="150px"/>

}
</p>

Step 2:-

 

In controller

[HttpPost]
publicActionResultIndex(HttpPostedFileBasefile12)
{
if(CheckImageFile(file12.FileName))
{
ViewBag.Success="s";
stringpath=System.IO.Path.Combine(Server.MapPath("~/Images"),System.IO.Path.GetFileName(file12.FileName));
file12.SaveAs(path);
ViewBag.Message="Fileuploadedsuccessfully";
ViewBag.Url="/Images/"+System.IO.Path.GetFileName(file12.FileName);
}
else{
ViewBag.Message="Pleaseselectproperfileforimagelikepng,jpeg,etc";
}
returnView();

}
[HttpGet]
publicActionResultIndex()
{
returnView();
}

Step 3:-
In View writ Javascript function
<scripttype="text/javascript">
$(function(){
alert("insertingimages");
//varurl="/Images/Tulips.jpg";
//$("#image").attr("src",url);

//alert('@ViewBag.Url');

if('@ViewBag.Success'=='s'){
alert('@ViewBag.Message');
$("#img1").attr("src",'@ViewBag.Url');
}
else{
alert('@ViewBag.Message');
$("#img1").attr("src",'/Images/no_image.gif');

}

})

</script>

 


Leave a comment

AJAX calls to ASP.NET MVC action methods using jQuery

It is best practice to use jQuery (or similar JavaScript library) for your web development. These libraries provide a powerful JavaScript API that allows you to interact with the DOM. There are many many differences between browsers and even between versions of the same browser. A well designed library, such as jQuery, will take care of these differences for you. You are then allowed to focus on coding your features and not on making sure your code is going to work in IE, Chrome, Safari, and Firefox.

In this post, I will cover how to use jQuery to call the action methods on your ASP.NET MVC controller using AJAX. I will not cover how to use jQuery to select and manipulate DOM elements. The later has been covered quite frequently elsewhere.

Getting Started

Using jQuery with the ASP.NET MVC framework is very easy. Most of you know that jQuery now ships with ASP.NET MVC. To use jQuery you must include the following script tag (usually in your Master Page or the HTML ‘head’ section:

1 <script src="<%= Url.Content("~/Scripts/jquery-1.3.2.js") %>" type="text/javascript"></script>

This will load the jQuery library from the content folder and make it available on the page.

Call An Action Method That Returns String Content

Imagine you have the following action method on a Test controller:

1 public string GetDateTimeString()
2 {
3     return DateTime.Now.ToString();
4 }

Note that the above method returns a string. To call this action method using jQuery, you can use the jQuery ‘get’ function as shown below:

1 var url = "/Monitor/Test/GetDateTimeString";
2 $.get(url, nullfunction(data) {
3     $("#getDateTimeString").html(data);
4 });

The jQuery ‘get’ method is a helper method that generates an AJAX GET request. The first parameter is the URL and the third is the callback function when the response is received. The callback function takes one parameter ‘data’ that holds the string content. The following is a screen shot of the resulting data:

image

Call An Action Method That Returns A String But Takes Parameters

This is really the same scenario as the previous case, except the action method expects a parameter. To set the action method parameter we will use the second parameter of the jQuery ‘get’ function. Imagine we have this action method on a Test controller:

1 public string ReverseTheString(string input)
2 {
3     char[] arr = input.ToCharArray();
4     Array.Reverse(arr);
5     return new string(arr);
6 }

Use the following JavaScript to call this method using AJAX:

1 var url = "/Monitor/Test/ReverseTheString";
2 var stringToReverse = "Bob Cravens";
3 $.get(url, { input: stringToReverse }, function(data) {
4     $("#reverseTheString").html(data);
5 });

Notice that the second parameter to the ‘get’ function now contains a list of key / value pairs. This example supplies one parameter, but can be extended to provide multiple parameters. The result of the above looks like the following:

image

Call An Action Method That Returns JSON And Takes Parameters

The action methods above returned simple strings. Now imagine you want to dynamically fetch more complex data. This is typically formatted in JSON. For example, imagine we want to fetch contact information from the server. More specifically let’s say you have the following ContactInfo class and GetContactInfo action method:

01 public class ContactInfo
02 {
03     public string FirstName { getset; }
04     public string LastName { getset; }
05     public string State { getset; }
06     public int Age { getset; }
07 }
08 public JsonResult GetContactInfo(int personId)
09 {
10     // Use personId to fetch info from repository.
11     //
12     // Fake it here.
13     ContactInfo contactInfo = new ContactInfo
14                                   {
15                                       FirstName = "Bob",
16                                       LastName = "Cravens",
17                                       State = "Wisconsin",
18                                       Age = new 43
19                                   };
20     return Json(contactInfo);
21 }

Notice the action method is now returning a ‘JsonResult’. This action method can be called using the following JavaScript:

1 var url = "/Monitor/Test/GetContactInfo";
2 var id = 123;
3 $.getJSON(url, { personId: id }, function(data) {
4     $("#name").html(data.FirstName + " " + data.LastName);
5     $("#state").html(data.State);
6     $("#age").html(data.Age);
7 });

Using Firebug we can sniff the response. A screen shot is shown below:

imageNotice the response data now has JSON format. The following was rendered in this example:

image

Post Data To An Action Method

Imagine you have a situation where you want to HTTP POST instead of GET data. For example, suppose you have data that you want to submit via AJAX. Assume for instance you have the following action method:

1 [AcceptVerbs(HttpVerbs.Post)]
2 public string RegisterUser(string firstName, string lastName)
3 {
4     // Use the parameters provided to register a new user.
5     return firstName + " " + lastName + " was successfully registered.";
6 }

This action method has attributes that only accept HTTP POST requests. To call this method using AJAX we can use the jQuery ‘post’ function as follows:

1 var url = "/Monitor/Test/RegisterUser";
2 var first = "Bob";
3 var last = "Cravens";
4 $.post(url, { firstName: first, lastName: last }, function(data) {
5     $("#registerUser").html(data);
6 });

Notice the ‘post’ function and the ‘get’ function take the same parameters. This is an example of an action method that requires two parameters and returns a string result. This results in the following:

image

Post Form Data

Let’s say you have the following form for submitting new contact information:

1 <form id="myForm" action="/Monitor/Test/FormPost" method="post">
2     <div>First Name: <input name="FirstName" type="text" value="Bob" /></div>
3     <div>Last Name: <input name="LastName" type="text" value="Cravens" /></div>
4     <div>Age: <input name="Age" type="text" value="43" /></div>
5     <input type="submit" value="Save Contact" />
6     <div id="postResult">?</div>
7 </form>

This from calls the ‘FormPost’ action method on the ‘Test’ controller for the ‘Monitor’ application. The following is the action method called when the form is submitted:

1 [AcceptVerbs(HttpVerbs.Post)]
2 public string FormPost(ContactInfo contactInfo)
3 {
4     return contactInfo.FirstName + " " + contactInfo.LastName + " (" + contactInfo.Age + ") has been saved.";
5 }

Notice the action method returns a string result. Now assume you want to submit this from using AJAX.  This is easily done using the following JavaScript:

1 var f = $("#myForm");
2 var url = f.attr("action");
3 var formData = f.serialize();
4 $.post(url, formData, function(data) {
5     $("#postResult").html(data);
6 });

This JavaScript shows the power of jQuery. With one ‘serialize’ call all the form’s input data is collected and ready to be sent. We can again sniff the post data using Firebug:

image

Notice the above action method takes a ‘ContactInfo’ (same as the one introduced earlier) object. No where in this code are we creating this type of object. So who is creating this object? This is the power of the ASP.NET MVC model binder in action. As long as the names (‘FirstName’, ‘LastName’, ‘Age’ in this example) of the input elements match the corresponding property names of the object the model binder will have no problem. The following is a screen shot of the rendered HTML after the form has been submitted:

image

Load an MVC Partial View

The server is often times the best place to generate your HTML content. Adding dynamically generated content based upon the current application state is often necessary. Suppose you have the following action method on your MVC Test controller:

1 public ActionResult MyPartialView(string info)
2 {
3     ViewData["info"] = info;
4     return View();
5 }

This action method is simplistic. It stored some ‘info’ data into the ViewData dictionary and then returns the following partial view.

1 <span>
2     Your Info: <%= Html.Encode(ViewData["info"]) %>
3 </span>

Again, this is a simple partial view that is dynamically generated to display your input info. This partial view can be loaded into the DOM using the jQuery ‘load’ function as follows:

1 var url = "/Monitor/Test/MyPartialView";
2 var info = "This is my information."
3 $("#partialView").load(url, { info: info });

Notice the ‘load’ method is a function attached to every jQuery element that is generated with a selector. The above method replaces the HTML of the element with ID of ‘partialView’ with the dynamically generated HTML from the MVC partial view. Using Firebug to sniff the response shows the following:

image

Notice the response is HTML. The results look like the following when rendered by the browser.

image

Summary

Using AJAX to call your ASP.NET MVC controller action methods is very simple using jQuery. The jQuery ‘get’, ‘getJSON’, ‘post’ and ‘load’ functions are easily used to call action methods and handle the returned data.

Action controller input parameters can be sent using JSON key / value notation. The important thing to remember is to match key names to the names of the input parameters. The ASP.NET MVC model binders can even handle matching key names to property names on more complex types.

Returned data types can be simple string, JSON data, or HTML rendered from partial views. This allows the JavaScript callback function to be flexible and designed for the situation. No sense in handling JSON if a simple string will do. If it is a better design to let the server generate the HTML this can be done. Or if you are using JavaScript templating and need JSON data that is also easy.


Leave a comment

Using JQuery for Controller method cal and loading partial view dynamically

for first dropdown in Controller

publicActionResultStore()
{
UserInfoService.UserInfoClientproxy=newUserInfoService.UserInfoClient();

ViewBag.CityList=newSelectList(proxy.GetCity());
string[]CityList=proxy.GetCity();

returnView(CityList);
}

in View

@Html.DropDownList("CityList",ViewBag.CityListasSelectList,"SelectCity",new{id="CityList1"})

now define another action for 2nd dropdown list

publicActionResultstoreList(stringCity)
{
UserInfoService.UserInfoClientproxy=newUserInfoService.UserInfoClient();

IEnumerable<Stores>Store=proxy.GetStoreByCity(City);
ViewBag.StoreList=fromsinStore
selectnewSelectListItem{Text=s.Name,Value=Convert.ToString(s.Id)};

returnPartialView("_StoreList");

}

create a partial view
@Html.DropDownList("StoreList",ViewBag.StoreListasSelectList,"selectstore",new{id="storelist1"})

in view
<scripttype="text/javascript">
$(function(){
$('#CityList1').change(function(){
varc=$('#CityList1').val();
//$('#partialDropDown').load('@Url.Action("storeList","User")',{city:c});
//get or post both will work
$.get("/User/storeList",{city:c},
function(data){
$("#UpdateableContent").html(data);
});

alert($('#CityList1').val());
});
})

</script>

in main VIew
<divid="UpdateableContent">
@*@Html.Partial("_PartialView1")*@
</div>


Leave a comment

1. Define a partial view like below:

<table>
<tr>
<td>
<label id="lbl1" >test</label>

<input type="text" />
</td>
</tr>
</table>

2:write an action method that will return that partial view
  public ActionResult UpdatePartial()
        {

            return PartialView("_PartialView1");
        }
3:Write this on main view
<script type="text/javascript">

    $(document).ready(function () {

        $.post("/User/UpdatePartial",
               function (data) {
                   $("#partialDropDown").html(data);
               });

    });

</script>

4: define a div with ID=partialDropDown where we will insert the total html of partial view.


Leave a comment

How to call Controller Method and populate DropDownList

 

 

STEP 1:-method in controller for populating the dropdownlist

publicActionResultstoreList(string City)
{
UserInfoService.UserInfoClientproxy=newUserInfoService.UserInfoClient();

IEnumerable<Stores>Store=proxy.GetStoreByCity(City);
ViewBag.StoreList=fromsinStore
selectnewSelectListItem{Text=s.Name,Value=Convert.ToString(s.Id)};

returnPartialView("_StoreList");

}

 

STEP 2:-this method should be called on first ddl change event in view page.

 

First ddl:

@Html.DropDownList("CityList",ViewBag.CityListasSelectList,new{id="CityList1"})

and JavaScript code to call method:-

<scripttype="text/javascript">
$(function(){
$('#CityList1').change(function(){
varc=$('#CityList1').val();
$('#partialDropDown').load('@Url.Action("storeList","User")',{city:c});
});
})

</script>

Step3:-define a div if that viewbag is null then not call the partial view else call the partial view

<divid="partialDropDown">
@if(ViewBag.StoreList!=null)
{
@Html.Partial("_StoreList")// this is the view name
}
</div>

Step:4:-define partial view

@Html.DropDownList("StoreList",ViewBag.StoreList as SelectList)

 

 


Leave a comment

Consuming a WCF Service with jQuery or ScriptManager

I recently created a working example of WCF service that is consumed by both a jQuery AJAX call and a ScriptManager AJAX call. I was interested to see how the WCF improvements offered by .NET 4 compared with the latest jQuery library (v1.7.1 at the time of writing). You candownload the solution’s source code or take a look through this post where I discuss the particulars of this comparison.

Before delving into the code I want to point out a few things; (1) I’ve cut out all of the extraneous code from this sample so what’s included is the bare essentials in order to get the sample working (unless otherwise indicated), (2) this post assumes you are familiar with WCF, AJAX, jQuery, and ScriptManager, and (3) I have avoided implementing a DataContract, again to keep it simple.

Solution

There are two projects in this solution, an ASP.NET Web Application which contains the jQuery and ScriptManager calls, and the Class Library which serves as the Service Library. The web application references the service library.

The solution’s source code (AJAXEnabledWCFService.zip) can be downloaded via Google Docs.

Service Library

For good practice I decoupled the service implementation from the presentation layer, hence having two projects rather than just the one web application. A much simpler alternative, recommended for very small projects, is to create an “AJAX-enabled WCF Service” item within the web application. This would actually have been fine but I wanted to expose a service within my web application that mapped to my WCF Service Library’s service and this wouldn’t have been possible with the aforementioned approach. In addition, I created a Class Library rather than a WCF Service Application as I prefer to add project code myself and not have to strip out a lot of unnecessary Visual Studio template code.

The Service Library contains a simple service with one method; GetAllCountries(), which accepts no parameters and returns a JSON-formatted response of country names. Note that I don’t have to explicitly state the response format as JSON is the default.

IEurope.cs

 

1 namespace ServiceLibrary.Countries
2 {
3     [ServiceContract(Namespace = "Countries")]
4     public interface IEurope
5     {
6         [OperationContract]
7         List GetAllCountries();
8     }
9 }

 

Europe.cs

 

01 namespace ServiceLibrary.Countries
02 {
03     public class Europe : IEurope
04     {
05         public List GetAllCountries()
06         {
07             List allCountries = new List();
08
09             allCountries.Add("Albania");
10             allCountries.Add("Andorra");
11             // More countries added.
12             allCountries.Add("United Kingdom");
13             allCountries.Add("Vatican City");
14
15             return allCountries;
16         }
17     }
18 }

 

Web Application

There is a short-list of files in the web application, the most important being the one which maps the AJAX calls to the Service Library; Europe.svc.

Europe.svc

 

1 <%@ ServiceHost Service="ServiceLibrary.Countries.Europe" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"%>

 

This one simple line has the Service attribute pointing at the Service Library service; Europe. Followed by the Factoryattribute that references the WebScriptServiceHostFactory which “automatically adds an ASP.NET AJAX endpoint to a service, without requiring configuration, in a managed hosting environment that dynamically activates host instances for the service in response to incoming messages” – MSDN.

Web.Config

 

1 <?xml version="1.0"?>
2 <configuration>
3     <system.web>
4         <compilation debug="true" targetFramework="4.0" />
5     </system.web>
6 </configuration>

 

If you’ve had some experience with WCF you’ll notice the most obvious difference is that there is absolutely no endpoint configuration settings. I’ve read, and been told, that you still need to keep the <standardendpoints> node and it’s child nodes, however I removed this from the solution and noticed no difference. The default values are adequate for this solution and the WebScriptServiceHostFactory does the remainder of the heavy lifting – you can start to see how much easier this is. Don’t get me wrong, I’d still recommend that developers implementing this type of code have a solid grasp of the ABCs of WCF as there are a lot of WCF considerations to address once you move away from your basic web application – security, performance, maintainability etc.

jQuery

Before I get into the JavaScript you can see that the <body> only contains a button, and a div for outputting my responses. The header contains a jQuery reference followed by a single function which is called by the buttons onclick event and performs the asynchronous HTTP request: $.ajax.

jQuery.aspx

 

01 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="jQuery.aspx.cs" Inherits="WebApplication.jQuery" %>
02 <html>
03 <head>
04     <title>jQuery</title>
05     <script src="Resources/JavaScript/jquery-1.7.1.min.js" type="text/javascript"></script>
06     <script type="text/javascript">
07         //<![CDATA[
08
09         function Test()
10         {
11             $.ajax(
12             {
13                 type: "POST",
14                 contentType: "application/json;charset=utf-8",
15                 url: "Services/Countries/Europe.svc/GetAllCountries",
16                 data: null,
17                 dataType: "json",
18                 beforeSend: function (jqXHR, settings)
19                 {
20                     $("#divOutput").append("<br/>Before send...");
21                 },
22                 success: function (response, status, jqXHR)
23                 {
24                     // The ".d" property is the name for the name/value JSON response.
25                     for (i in response.d)
26                         $("#divOutput").append("<br/>" + response.d[i]);
27
28                     $("#divOutput").append("<br/>Success.");
29                 },
30                     error: function (jqXHR, status, error)
31                 {
32                     $("#divOutput").append("<br/>Error " + jqXHR.responseText);
33                 },
34                 complete: function (jqXHR, status)
35                 {
36                     $("#divOutput").append("<br/>Complete " + status + ".");
37                 }
38             });
39         }
40
41         // ]]>
42     </script>
43 </head>
44 <body>
45
46     <h1>Using jQuery</h1>
47
48     <form runat="server">
49
50         <p>
51             <input type="button" value=" Test " onclick="return Test();" />
52         </p>
53
54         Output:
55         <div id="divOutput"></div>
56
57     </form>
58
59 </body>
60 </html>

 

The jQuery AJAX API has an array of functions and methods, some of which are employed in the code above. There is one API function in particular; beforeSend which isn’t required but I’ve included it as it shows that you can use it to start up a loading animation, for example, while you’re waiting to receive an asynchronous response.

As the code reads – a click event fires a call to the JavaScript Test() method which makes an asynchronous AJAX POST request to GetAllCountries() exposed by the web application’s service mapping, which in turn calls the Service Library’s (similarly named) operation contract. The response returned is then dynamically inserted into the specified<div>. I’ve purposefully excluded posting any request data as I wanted to keep this simple. Once everything is wired up you can see it’s not too difficult to implement or understand.

ScriptManager

Contained within the System.Web.Extensions assembly (System.Web.UI namespace) is the ScriptManager class which “manages ASP.NET Ajax script libraries and script files, partial-page rendering, and client proxy class generation for Web and application services” – MSDN. It’s a powerful resource, which like jQuery, cuts down on a significant amount of development time and heavy lifting. You can see the tag at the bottom of the following code sample, referencing the web application’s .svc file. This allows you to make an asynchronous call to the GetAllCountries() method as illustrated in the JavaScript’s Test() function.

ScriptManager.aspx

 

01 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ScriptManager.aspx.cs" Inherits="WebApplication.ScriptManager" %>
02 <html>
03 <head>
04     <title></title>
05     <script type="text/javascript">
06         //<![CDATA[
07
08         function Test()
09         {
10             Countries.IEurope.GetAllCountries(OnRequestComplete, onError);
11         }
12
13         function OnRequestComplete(response, state)
14         {
15             for (i in response)
16                 document.getElementById("divOutput").innerHTML += "<br/>" + response[i];
17         }
18
19         function onError()
20         {
21             document.getElementById("divOutput").innerText = "Error";
22         }
23
24         // ]]>
25     </script>
26 </head>
27 <body>
28
29 <h1>Using ScriptManager</h1>
30
31     <form runat="server">
32
33         <p>
34             <input type="button" value=" Test " onclick="return Test();" />
35         </p>
36
37         Output:
38         <div id="divOutput"></div>
39
40          <asp:ScriptManager runat="server">
41              <Services>
42                  <asp:ServiceReference Path="~/Services/Countries/Europe.svc" />
43              </Services>
44          </asp:ScriptManager>
45
46     </form>
47 </body>
48 </html>

 

The first thing that stands out when comparing the two methods is the amount of coding required. ‘Yes’ you don’t get a nicebeforeSend type method with ScriptManager but look at how much less code there is.

If you look at the ScriptManager.aspx page’s source code from within your browser you’ll see (not too far from the bottom) a script reference to the web application’s service file:

 

1 <script type="text/javascript" src="Services/Countries/Europe.svc/jsdebug"></script>

 

If you enter this into the browser’s address bar you’ll get back some script which contains the JavaScript proxy code that does the bulk of the work. You can see how this dynamically generated code is tucked away so you can focus on what’s important when building your solution. If you remove the “debug” part from the end of the srcattribute’s value so you only have:

 

1 <script type="text/javascript" src="Services/Countries/Europe.svc/js"></script>

 

You’ll notice that you get back the JavaScript less the debugging code.

Comparison of jQuery and ScriptManager

Which approach is “better”? Personally I think it depends on a number of factors such as the technologies you’re encouraged to include (or avoid), the technical skills inherent to the developer building this part of your solution, whether you need to implement one of the additional jQuery.ajax() methods not made available via ScriptManager etc. At the end of the day it’s nice to know there is more than one option available when making WCF service calls from JavaScript. And I don’t see jQuery or ScriptManager disappearing anytime soon so both approaches are certainly future-proof … for the next few years anyway.

Download Source Code

The solution’s source code (AJAXEnabledWCFService.zip) can be downloaded via Google Docs.


Leave a comment

WCF BINDING

In this article we will discuss endpoints which consists of Address, Binding and Contract.

.

WCF–Address-Binding-Contract.jpg

Endpoint

An Endpoint is a piece of information that tells WCF how to build the runtime communication channels to send and receive messages. An endpoint consists of the three things address, binding and contract.

Endpoint.jpg

Address

Address – Where – Where to send messages

An Address is a unique Uniform Resource Locator (URI) that identifies the location of the service. It defines the network address for sending and receiving the messages. It is divided into four parts:

Address.jpg

Binding

Binding – How – How to send messages

A Binding specifies which transport protocol to use, what message format and which any of the ws* protocols we want to use to a particular endpoint.

BasicHttpBinding

  • Replacement for earlier Web Service based on ASMX (Active Server Methods)
  • Supports:
  • HTTP – Hypertext Transfer Protocol
  • HTTPS – Hypertext Transfer Protocol over SSL
    • MTOM – Message Transmission Optimization Mechanism encoding methods.

wsHttpBinding

  • Uses SOAP over HTTP and supports reliability, transactions and security over the internet.
  • Supports:

  • HTTP – Hypertext Transfer Protocol
  • HTTPS – Hypertext Transfer Protocol over SSL
    • MTOM – Message Transmission Optimization Mechanism encoding methods.

wsDualHttpBinding

  • Used for duplex service contract because it supports bidirectional communication.

webHttpBinding

  • Sends information directly over HTTP or HTTPS without creating a SOAP envelope
  • It is a good choice when SOAP is not required by the client

NetTcpBinding

  • Used to send binary-encoded SOAP messages from one computer to another
  • Uses TCP (Transmission Control Protocol) and includes support for reliability, transactions and security

NetPeerTcpBinding

  • Used for peer-to-peer communication over TCP
  • Communication should occur between two or more computers

netNamedPipeBinding

  • Binary encoded SOAP messages are sent over named pipes
  • Used on a single WCF computer

netMSMQBinding

  • Queued binding is used to send binary-encoded SOAP messages over MSMQ
  • Communication should occur between two computers

Contract

A Contract provides the additional detail about the structuring contents of the various messages that will be used by the various operations exposed to the particular endpoints. For example we create a service “TopupService”, the interface used to define the service is “ITopupService” and the project name is “Utility”. The contract for this service would be Utility.ITopupService.