WCF服务将数据填充到ASP.net下拉列表(学习WCF服务)

时间:2016-10-27 19:22:37

标签: c# asp.net wcf

我正在尝试学习WCF服务,最终合并到我们的一个网站。

我在我的数据库中创建了一个名为[TestTable]的测试表 我已经能够从视觉工作室中创建的测试站点成功地将数据写入表中。

我现在正在尝试从数据库填充下拉列表。在这种情况下,所有州的列表。

似乎有些东西我不知道了。我可以调用该服务,它将显示WCF测试客户端中的所有状态;但是,我似乎无法弄清楚如何将它返回的列表附加到ASP.net下拉列表中。

这是我的IService1.cs

odbcConnect

这是GetAllStates的Service1.svc.cs

[ServiceContract]
public interface IService1
{

    [OperationContract]
    //string GetData(int value);
    string InsertApplicantDetails(ApplicantDetails appInfo);

    [OperationContract]
    List<US_States> GetAllStates();

    //CompositeType GetDataUsingDataContract(CompositeType composite);

    // TODO: Add your service operations here

}

在测试网站中,我创建了名为“dropdownStates”的下拉列表 我添加了ServiceReference,它正在工作,因为我可以向数据库提交值。 我还为下拉列表创建了一个Load()事件。

这是我的测试页面。

public List<US_States> GetAllStates()
    {
        using (JobSeekersEntities db = new JobSeekersEntities())
        {
            var q = (from us_states in db.US_States
                     orderby us_states.abbr ascending
                     select us_states);

            List<US_States> list_States = q.ToList<US_States>();

            return list_States.ToList();

        }
    }

{     ServiceReference1.Service1Client objCon = new ServiceReference1.Service1Client();

public partial class TestSubmission : System.Web.UI.Page

}

非常感谢任何帮助。谢谢你的时间。

2 个答案:

答案 0 :(得分:1)

首先确保您已定义正确的DataContract和服务合同。 在以下示例中,我定义了具有2个属性的美国州。 注意[OperationContract]和[DataContract]声明!

hunkp

接下来向您的项目添加WebService引用并进行如下调用: (将StateName绑定到Text,将StateId绑定到Value)

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        List<US_States> GetAllStates();

    }


    [DataContract]
    public class US_States
    {
        [DataMember]
        public int StateId { get; set; }

        [DataMember]
        public string StateName { get; set; }
    }
}

最后服务:

    protected void dropdownStates_Load(object sender, EventArgs e)
    {
        ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
        dropdownStates.Items.Clear();
        dropdownStates.DataSource = client.GetAllStates();
        dropdownStates.DataTextField = "StateName";
        dropdownStates.DataValueField = "StateId";
        dropdownStates.DataBind();
        client.Close();
    }

答案 1 :(得分:1)

using(ServiceReference1.Service1Client client = new ServiceReference1.Service1Client())
{
        dropdownStates.Items.Clear();
        dropdownStates.DataSource = client.GetAllStates();
        dropdownStates.DataTextField = "Name";
        dropdownStates.DataValueField = "Id";
        dropdownStates.DataBind();
}

您只需将Dropdown DataSource设置为列表即可。将text和datavale字段设置为您希望显示为项目的内容以及它所支持的值,最后调用DataBind。

相关问题