如何从服务方法中获取返回值?

时间:2011-05-31 09:25:19

标签: silverlight wcf

我对silverlight和WCF全新。仍在阅读在线资料并尝试编写一些代码来开始。 :)

我的问题是,我想将数据插入数据库,我的insert方法返回一个bool。如何在按钮单击事件中捕获silverlight中的返回值并向用户显示确认消息。

我的服务代码是:

[OperationContract]
    public bool insertData(string Name, string Address, string cType, string postcode, string city, string phone, string email)
    {
        bussAppDataContext dc = new bussAppDataContext();
        TestTable tt = new TestTable();


        tt.CompanyName = Name;
        tt.Address = Address;
        tt.CompanyType = cType;
        tt.Postcode = postcode;
        tt.City = city;
        tt.Telephone = phone;
        tt.Email = email;

        dc.TestTables.InsertOnSubmit(tt);
        dc.SubmitChanges();
        return true;

    }

Silverlight客户端代码是:

private void btnSend_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        FirstServiceReference.FirstServiceClient webServc = new FirstServiceReference.FirstServiceClient();

webServc.insertDataAsync(txtCName.Text.Trim(),txtAddress.Text.Trim(),cmbCType.SelectedValue.ToString(),txtPostcode.Text.Trim(),txtCity.Text.Trim(),txtPhone.Text .Trim(),txtEmail.Text.Trim());

}

1 个答案:

答案 0 :(得分:2)

所有webservice调用在silverlight中都是异步的,因此您需要为insertDataCompleted事件添加处理程序。操作完成后调用此事件。 像这样:

webServc.insertDataCompleted += MyHandler;
webServc.insertDataAsync(txtCName.Text.Trim(), txtAddress.Text.Trim(), cmbCType.SelectedValue.ToString(), txtPostcode.Text.Trim(), txtCity.Text.Trim(), txtPhone.Text.Trim(), txtEmail.Text.Trim());

}

private void MyHandler(object sender, MyEventArgs args) {}

args的结果是布尔值。 看看Calling web services with Silverlight Tim Heuer

希望这有帮助。

BR,

TJ