0

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

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:

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

The C# code behind from the ASPX url in the above jQuery statement:

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. Thanks again for any help you can provide.

DT74
  • 21
  • 6

2 Answers2

1

This has to be a bad 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. 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. 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):

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? Who/What receives it? Nobody and nothing receives it, at least not in any meaningful or proper way.

Now, back to your incorrect 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. 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. This client could be a mobile app, a web app, a web page, some kiosk device, whatever.

ASP.NET can serve data to client requests, that is what ASP.NET does and it runs on a server to serve requested resources. And you could even server data from a Web Form .aspx resource's code behind to a client AJAX request. 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...

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. That is where that awful saying "code behind" comes from, its the code behind for particular .aspx Web Form.

Use a "Handler(s)" for your AJAX calls. This is a resource you can create in Visual Studio, Add New => Handler, the extension is .ashx. You can create endpoints that you can call with a url and return data. 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.

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. 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. It was built to allow Windows Forms developers to more easily migrate to develop Web Applications. 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. 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. 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. P.S. 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.

Brian Ogden
  • 18,439
  • 10
  • 97
  • 176
  • You are correct, I did have the link wrong (products was incorrect)! It's been a long couple of days for me, but I also thank you for the valuable information. Right now, I am not in an IT career field, I am tinkering and learning. I messed around slightly with Web APIs but haven't gotten to the point where I can utilize them just yet. I am sure you can tell, I am just learning the syntax at this point so I appreciate the feedback. I will definitely check out the link you posted. – DT74 Oct 21 '19 at 21:42
  • I work maintaining a legacy website built on aspx WebForms. It uses both ashx and WebMethods. IMHO this is not the worst thing in the world; it uses WebMethods to service Ajax calls that are necessarily unique to the WebForm in question and ashx for generalised calls. This gives me far fewer headaches than (for example) Page_,Load events running to thousands of lines of code. I would therefore be rather less dogmatic. – Jonathan Willcock Oct 22 '19 at 01:50
  • @JonathanWillcock I kind of disagree that I am being very dogmatic/ If you think I am being dogmatic because I recommend not making a client call to a Web Method in a Web Form code behind, fair enough. I am, in part, trying to keep things simple for the OP who is learning and not trying to overwhelm with different acceptable patterns. – Brian Ogden Oct 22 '19 at 02:15
  • @JonathanWillcock I will generally disagree with your use of Web Methods. Sure you pattern is not a problem and does not hinder your code. But you violate the Single-responsibility Principle for no real added value. Code Behind serves the initiation & re-rendering logic for a Web Form, end of story. Create a .ashx handler of the same name or similar as the Web Form and put in the same folder as the Web Form to serve AJAX calls made for the client side rendering of the Web Form. Web Methods serve tightly coupled code that cannot be accessed outside of the Code Behind I would think is only need – Brian Ogden Oct 22 '19 at 02:18
  • @Brian Ogden Maybe I didn't make myself clear. This is not my code. It is legacy, that I maintain. To me consistency of approach is paramount. I don't mind my predecessors' conventions, because they were consistent: 1-1 WebMethod in same file; many-1 separate ashx. The point for me in maintaining this, is that I do usually know where to look for something, and that to me is most important, given that the site has c. 400 aspx pages alone, without counting library routines, ashx etc. – Jonathan Willcock Oct 22 '19 at 03:51
0

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.

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

            });
        });
});
Faseeh Haris
  • 669
  • 1
  • 11
  • 29
  • Thanks for the code, I still haven't gotten it to work just yet (even after fixing the link that Brian pointed out as incorrect) but I believe it is on the back end side. You made a good point about dynamic vs assigning by ID. – DT74 Oct 21 '19 at 21:53