views:

135

answers:

3

Hi all,

I have a class at server-side like this :

public class Address
{
    public Address(string countryCode)
    {
        this._CountryCode = countryCode;
    }

    private string _CountryCode = string.Empty;
    public string CountryCode
    {
        get { return _CountryCode; }
        set { _CountryCode = value; }
    }

}

and I have a method that called by Ajax methods :

[AjaxMethod]
public static Address ValidateAddress(Address address)
{
   // Some logic here...
   return address;
}

And I want to call this method in client side, but how can I instantiate the Address class in client side ? I do not want to define a class named Address in javascript file.

<script>

function valaddress(){ 

  var address = new Address(); // I'm asking here ??
  address.CountryCode = 90;

  // This part is ok, no problem in here : 
  var validatedAddress = AddressControlDataHelper.ValidateAddress(address).value; 

}

</script>

Are there a way to do this ? or do I need to write my Address class in javascript ?

thanks for your help !

+2  A: 

You are going to have to serialize the object first. One way to do this is with JSON (Javascript Object Notation) - here is a tutorial on how that works. EDIT: (Actually that tutorial is quite confusing and a bit outdated - try this one for a more direct, up-to-date approach.)

Andrew Hare
thanks, I'll check the article.
Canavar
+5  A: 

var address = { CountryCode: "1" }

That should do the trick

<script>
  function valaddress(){ 

      var address = { 
          CountryCode: "90"
      };

      // This part is ok, no problem in here : 
      var validatedAddress = 
       AddressControlDataHelper.ValidateAddress(address).value; 

  }
</script>
Bob
exacly what I want, thanks !
Canavar
No problem, glad it helped!
Bob
A: 

Using the .net AJAX extensions, you can add the GenerateScriptType tag above, for example, your server side ValidateAddress()

[GeneratScriptType(typeof(Address)]

The server would send the necessary js down to the client so you could make the js call

var address = new nameofyournamespace.Address()

See the msdn GenerateScriptTypeAttribute reference

David Archer