Which ASP.NET Page event is the best place for this type of code?
I have a relatively simple page that will do most of its operations on the client side using Javascript or JQuery. However, initially I do need to retrieve some data from the DB server based on QueryString parameters.
I plan on passing this data in the form of a JSON string to the script by an old-fashioned ASP manner ( var severData = <%=MyPublicData %>) block where MyPublicData is defined in CodeBehind as: Public string MyPublicData;
The question is, which event in the ASP.NET page lifecycle is the best for this? Page_Init ? Page_Load? Also, is it worth the effort to do this in ASP.NET MVC. I did look at this possiblity but it seemed a little too much for a simple page like this where I 开发者_Go百科do more 90% of the work on the client. Any thoughts on this?
Page_Load is more appropriate, but either will work.
It's very difficult to say if MVC is more appropriate for you application than webforms without knowing more about the application. However, if you don't want to abstract away the traditional web model then I'd go with MVC.
This kind of simple property or field assignment can go anywhere in the lifecycle. For lack of any other reason, you might as well stick it in Page_Load
, since that method is usually waiting for you in the code-behind anyway.
well, on the contrary, if it uses mostly javascript with jQuery, I would recommend you to use MVC. you will not have any problem with the ids for instance. There are workaround to use jQuery with webforms, but it is never perfectly clean regarding selecting the DOM.
MVC : a single action method where you will retrieve your data (preferably from a small repository) and 1 view where you display your data with total control over your html elements. and jQuery will just fit perfectly for your clientside work.
You can get either to work; you can write public variables/fields to the client in ASP.NET web forms, although MVC has an edge due to the way it renders the UI.
So for MyPublicData, you could assign it a value at any part of the lifecycle; you can assign it in code-behind to a label or something like that, or if it's JS markup you can write it out using Page.ClientScript.RegisterStartupScript or RegisterClientScriptBlock... so you have multiple options.
In MVC, you would assign the value in the controller and render it in the UI, or with JQuery you can do controller requests real easy with $.ajax.
精彩评论