如何从www.example.com中的数据库填充“select”asp.net

3xiyfsfu  于 2023-03-24  发布在  .NET
关注(0)|答案(7)|浏览(149)

我有一个html控件select

<select id="Select1" runat="server" name="D1">
    <option></option>
 </select>

如何使用C#JavaScript/jQuery/JSONSQL Server数据库中的数据填充到它?
请不要发布关于如何填充asp:DropDownList的答案,因为我已经知道如何做到这一点,我必须使用select控件。

vybvopom

vybvopom1#

aspx:

<select id="Select1" runat="server" name="D1">

  </select>

代码隐藏:

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      string ConnectString = "server=localhost;database=pubs;integrated security=SSPI";
      string QueryString = "select * from authors";

      SqlConnection myConnection = new SqlConnection(ConnectString);
      SqlDataAdapter myCommand = new SqlDataAdapter(QueryString, myConnection);
      DataSet ds = new DataSet();
      myCommand.Fill(ds, "Authors");

      Select1.DataSource = ds;
      Select1.DataTextField = "au_fname";
      Select1.DataValueField = "au_fname";
      Select1.DataBind();
   }
}
szqfcxe2

szqfcxe22#

function GetItems() {

var items;

    $.getJSON("/api/MethodName/" + id(Optional), function (data) {
        $.each(data, function (key, val) {
            items += "<option value='" + val.id+ "'>" + val.value+ "</option>";    
        });

        var header = '<option value=\'\'>Select...</option>';
        $('#Select1').html(header + items);
    });

};

您可以使用asp.netwebapi for json,它非常简单和快速

58wvjzkj

58wvjzkj3#

你可以 AJAX 中使用json,但是你必须使用一些webservice从服务器返回json。

$.ajax({
   url:'/path/to/webservice/method',
   type:'POST',
   dataType: 'json',
   success: function(data){
       $.each(data, function(i, item){
          $('<option value="'+item.val+'">'+item.text+'</option>').appendTo('#Select1');
       });
   },
   error: function(){
      console.log('err')
   }
});
bnl4lu3b

bnl4lu3b4#

在代码隐藏中:

string options = string.Empty; 
 using (SqlConnection sql_conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstr"].ToString()))
        {
            SqlDataAdapter sql_adapter = new SqlDataAdapter("select Value, Name from YourTable", sql_conn);
            DataSet ds = new DataSet();
            sql_adapter.Fill(ds, "TempTable");

            foreach (DataRow row in ds.Tables["TempTable"].Rows)
            {
                options = "<option value='" + row["Value"] + "'>" + row["Name"] + "</option>";
            }
            sql_conn.Close();
           return options;
        }

然后你可以使用jquery:

$.get(url, function (data) {        
        $('#Select1').html(data);
    });
ijxebb2r

ijxebb2r5#

你可以用中继器

<select>
<asp:Repeater ID="Repeater1" runat ="server" DataSourceID="SqlDataSource1">
    <ItemTemplate>
        <option value='<%# Eval("ID")%>'> <%# Eval("ITEMNAME")%></option>
    </ItemTemplate>
</asp:Repeater>
</select>
xvw2m8pv

xvw2m8pv6#

using (SqlConnection con = new SqlConnection("Data Source = [HostName]; Initial Catalog = CustomerOrders; Integrated Security = true"))
            {
                SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
                con.Open();

                dropDownList.DataSource = cmd.ExecuteReader();
                dropDownList.DataTextField = "Name";
                dropDownList.DataValueField = "Name";
                dropDownList.DataBind();
            }
rjjhvcjd

rjjhvcjd7#

//Controller 
    public IActionResult Create()
    {
        User user = new User();
        ViewBag.items = new SelectList(db.Professions, "Id", "Name", user.ProfessionId);
        return View();
     }

   //View
    @model DbOneToMore.Data.User
    <select asp-for="ProfessionId" >
            <option selected disabled>Choose</option>
        @foreach (SelectListItem i in ViewBag.Items)
            {
            <option value="@i.Value">
                    @i.Text
                </option>
            }
        </select>

[1]:dropdownlist set selected value in MVC3 Razor

相关问题