简体   繁体   English

如何使用 ZD7EFA19FBE7D2372FD5ADB6D6024 后面的 jQuery 填充 HTML select 框(下拉列表)

[英]How do you populate a HTML select box (drop down list) using jQuery from C# code behind

I am trying to populate a drop down on a HTML front end and the C# code behind from a blank ASPX page utilized as a local server using jQuery/AJAX.我正在尝试填充 HTML 前端的下拉列表和 C# 代码后面的空白 ASPX 页面,该页面用作使用 jQuery/AJAX 的本地服务器。 I am new to this, so please keep that in mind.我是新手,所以请记住这一点。

I have tried multiple different approaches but none have been successful so far.我尝试了多种不同的方法,但到目前为止都没有成功。 Here is the code I have so far:这是我到目前为止的代码:

The jQuery statement: jQuery 声明:

var uri = 'http://localhost:60970/ItemProc.aspxproducts';

    $(document).ready(function () {
        // Send an AJAX request
        $.getJSON(uri)
            .done(function (data) {
                // On success, 'data' contains a list of products.
                $.each(data, function (key, item) {
                    // Add a list item for the product.
                    $('<option>', { text: item }).appendTo($('#test'));
                });
            });
    });

The HTML drop down list that I want to populate:我要填充的 HTML 下拉列表:

<h2>All Products</h2>
<select id="test" />

The C# code behind from the ASPX url in the above jQuery statement:上述 jQuery 语句中的 ASPX url 后面的 C# 代码:

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            String outstr = "";
            outstr += "1";
            outstr += "2";
            outstr += "3";
            Response.Write(outstr);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
 }

I expect the final outcome to be the test drop down list populated with the 1, 2, 3 from the C# code behind but have not been successful in anything that I have tried thus far.我希望最终结果是测试下拉列表,其中包含来自 C# 代码的 1、2、3,但到目前为止我尝试过的任何事情都没有成功。 Thanks again for any help you can provide.再次感谢您提供的任何帮助。

This has to be a bad uri: http://localhost:60970/ItemProc.aspxproducts这一定是一个糟糕的 uri: http://localhost:60970/ItemProc.aspxproducts

So that is one thing that is wrong.所以这是错误的一件事。

Next more fundamental problem is your using an ASP.NET Web Forms Page Lifecycle hook/event to serve data and you think that this is an exposed endpoint that your Jquery could call via AJAX and/or callable with Javascript client side AJAX. Next more fundamental problem is your using an ASP.NET Web Forms Page Lifecycle hook/event to serve data and you think that this is an exposed endpoint that your Jquery could call via AJAX and/or callable with Javascript client side AJAX. Thi is not the case.情况并非如此。

The Page_Load event is fired server side, on a Windows Server running IIS and ASP.NET Web Forms application. The Page_Load event is fired server side, on a Windows Server running IIS and ASP.NET Web Forms application. Your implementation of Page_Load will do things like the infamous and rather loathed (if you have done anything newer than ASP.NET Web Forms in 15 years):您对 Page_Load 的实现将做一些臭名昭著且令人厌恶的事情(如果您在 1 年内做了比 ASP.NET Web Forms:

if(!IsPostBack) {
//init some data from SQL and bind to a WebForms DataGrid or something like that for example
}

Your response in your Page_Load goes where?您在Page_Load中的响应去了哪里? Who/What receives it?谁/什么接收它? Nobody and nothing receives it, at least not in any meaningful or proper way.没有人,也没有人接受它,至少不是以任何有意义或适当的方式。

Now, back to your incorrect uri.现在,回到你不正确的 uri。 The first obvious reason it is incorrect is because of the format: http://localhost:60970/ItemProc.aspxproducts There is no way this is a valid resource: ItemProc.aspxproducts.它不正确的第一个明显原因是格式: http://localhost:60970/ItemProc.aspxproducts这不可能是有效资源:ItemProc.aspxproducts。 I won't elaborate on this here, hopefully this will start to make sense.我不会在这里详细说明这一点,希望这将开始有意义。

Now, what you are trying to do is call an end point and get a data response.You are using jQuery to perform an AJAX call to an endpoint, more importantly you are making an AJAX call from a client.现在,您要做的是调用端点并获得数据响应。您正在使用 jQuery 对端点执行 AJAX 调用,更重要的是,您正在从客户端进行 AJAX 调用。 This client could be a mobile app, a web app, a web page, some kiosk device, whatever.这个客户端可以是一个移动应用程序、一个 web 应用程序、一个 web 页面、一些信息亭设备等等。

ASP.NET can serve data to client requests, that is what ASP.NET does and it runs on a server to serve requested resources. ASP.NET 可以为客户端请求提供数据,这就是 ASP.NET 所做的,它在服务器上运行以提供请求的资源。 And you could even server data from a Web Form.aspx resource's code behind to a client AJAX request.您甚至可以将来自 Web Form.aspx 资源代码的数据服务于客户端 AJAX 请求。 There is an attribute you can use to expose a Web Form's code behind method as an endpoint on the Windows server, so that it can be called client side...您可以使用一个属性将 Web 表单的代码隐藏方法公开为 Windows 服务器上的端点,以便可以将其称为客户端...

But don't do that, use the.aspx Web Form's code behind in a single purpose manner, the code behind is there to work with that.aspx Web Form.但是不要那样做,使用.aspx Web 表单后面的代码以单一目的方式使用,后面的代码可以与 that.aspx Web 表单一起使用。 That is where that awful saying "code behind" comes from, its the code behind for particular.aspx Web Form.这就是那个可怕的说法“背后的代码”的来源,它的代码背后是 specific.aspx Web 表格。

Use a "Handler(s)" for your AJAX calls.为您的 AJAX 调用使用“处理程序”。 This is a resource you can create in Visual Studio, Add New => Handler, the extension is.ashx.这是一个可以在Visual Studio中创建的资源,Add New => Handler,扩展名为.ashx。 You can create endpoints that you can call with a url and return data.您可以创建可以使用 url 调用的端点并返回数据。 This way there will be no confusion between code that is tied to a Web Form and code that is there to serve AJAX calls.这样,与 Web 表单相关联的代码和用于 AJAX 调用的代码之间就不会混淆。

Here is a great simple example to follow. 这是一个很好的简单示例。

By the way, I know I will probably be voted down for this part of my answer but it is still worth it to share with you: Do not use ASP.NET Web Forms or ASP.NET MVC for your frontend User Interface/web needs. By the way, I know I will probably be voted down for this part of my answer but it is still worth it to share with you: Do not use ASP.NET Web Forms or ASP.NET MVC for your frontend User Interface/web needs. Its fine to use ASP.NET for a middle tier but using Web Forms to render/bind UI components or ASP.NET MVC Razor, for that matter, in a software engineering life path is a bad direction. Its fine to use ASP.NET for a middle tier but using Web Forms to render/bind UI components or ASP.NET MVC Razor, for that matter, in a software engineering life path is a bad direction. ASP.NET Web Forms was bad from the start: brittle, complex, obscuring the way HTTP, HTML, CSS and Javascript worked. ASP.NET Web Forms was bad from the start: brittle, complex, obscuring the way HTTP, HTML, CSS and Javascript worked. It was built to allow Windows Forms developers to more easily migrate to develop Web Applications.它旨在允许 Windows Forms 开发人员更轻松地迁移以开发 Web 应用程序。 ASP.NET MVC was an improvement, but, in the end, the same thing: this tightly coupled obfuscation to how a web app works and runs on clients, like web browsers, that only read HTML/CSS and Javascript. ASP.NET MVC was an improvement, but, in the end, the same thing: this tightly coupled obfuscation to how a web app works and runs on clients, like web browsers, that only read HTML/CSS and Javascript. In this day and age, any contemporary front-end, worth it's weight, is a strongly independent layer, decoupled, calling APIs.在这个时代,任何当代前端,值得它的重量,都是一个高度独立的层,解耦,调用 API。 The contemporary frontend builds independently, can often be heavily tested independently, and is very naturally modular with many single purpose, reusable building block UI components.现代前端是独立构建的,通常可以独立进行大量测试,并且非常自然地模块化,具有许多单一用途、可重用的构建块 UI 组件。 Use ASP.NET Handlers or Controllers to serve as the APIs, sure, preferably use ASP.NET Core running on Linux in Containers if you are going to use ASP.NET at all. Use ASP.NET Handlers or Controllers to serve as the APIs, sure, preferably use ASP.NET Core running on Linux in Containers if you are going to use ASP.NET at all. But in NO way use ASP.NET WebForms <% WTF %> or @Html.TextBoxFor(I am basically the same thing as Web Forms in a cuter syntax) ever again and you will thank me for it later.但决不能使用 ASP.NET WebForms <% WTF %> 或 @Html.TextBoxFor(我与 Web Z6450242531912981C3683CAE88A32A6 基本相同) PS you can easily integrate React.js in a ASP.NET Web Forms or ASP.NET MVC application for new features so legacy existing code isn't much of an excuse. PS you can easily integrate React.js in a ASP.NET Web Forms or ASP.NET MVC application for new features so legacy existing code isn't much of an excuse.

There may be some change in below code with respect to your code behind and your logic.关于您的代码和逻辑,下面的代码可能会有一些变化。 Please use below code for your problem statement.请使用以下代码作为您的问题陈述。 It will be more easy for you to create Its dynamic HTML and then assign to select by ID.您可以更轻松地创建其动态 HTML,然后通过 ID 分配给 select。

 var uri = 'http://localhost:60970/ItemProc.aspxproducts';

$(document).ready(function () {
    // Send an AJAX request
    $.getJSON(uri)
        .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
                // Add a list item for the product.
                 var opt ='';
                  for(var i=0;i<item.length;i++) // you can use length of items
                   {
                    opt +='<option>'+ item.text;
                    opt +='</option';
                   }    
                   $('#test').append(opt);

            });
        });
});

How about doing a search using google or just a stackoverflow search box?使用 google 或仅使用 stackoverflow 搜索框进行搜索怎么样? Duplicated jQuery: Best practice to populate drop down?重复的 jQuery:填充下拉列表的最佳实践?

I think you can find what you want here.我想你可以在这里找到你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM