如何在不在JavaScript中定义类的情况下创建类?

时间:2009-03-02 13:35:08

标签: c# asp.net javascript

我在服务器端有一个类,如下所示:

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

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

}

我有一个通过Ajax方法调用的方法:

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

我想在客户端调用此方法,但是如何在客户端实例化Address类?我不想在JavaScript文件中定义名为Address的类。

<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>

有办法做到这一点吗?或者我需要在JavaScript中编写我的Address类吗?

3 个答案:

答案 0 :(得分:5)

var address = { 
    CountryCode: "1"
}

应该做的伎俩

<script>
  function valaddress(){ 

      var address = { 
          CountryCode: "90"
      };

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

  }
</script>

答案 1 :(得分:2)

您必须首先序列化对象。一种方法是使用JSON(Javascript对象表示法) - here is a tutorial on how that works. 编辑:(实际上该教程非常混乱,有点过时了 - 尝试this one for a more direct, up-to-date approach.

答案 2 :(得分:0)

使用.net AJAX扩展,您可以在上面添加GenerateScriptType标记,例如,您的服务器端ValidateAddress()

[GeneratScriptType(typeof(Address)]

服务器会将必要的js发送到客户端,以便你可以调用js

var address = new nameofyournamespace.Address()

请参阅msdn GenerateScriptTypeAttribute reference