I have this error: "Object reference not defined for an instance of an object."
What I've tried was to create an instance of the class and, through it, try to access the gridview passing a DataSet to make the Bind.
The class is consumed via AJAX (AJAX.PRO)
Example of what I did:
public partial class Exemplo : InternalBasePage
{
[AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.Read)]
public static string SalvarRegra(JavaScriptArray DataRule, string NameRule)
{
Exemplo exemplo = new Exemplo();
DataSet ds = new DataSet();
exemplo.GRID.DataSource = ds;
}
You so called static class is NOT a web page, nor a web method.
If you want to add a web method to a existing web page, then do so, and that web method is then free to use that static class.
But, a general class, or in fact any class you build is just that - a class and hunk of code. But, as such it has really ZERO to do with a web page, or even a web method.
And it not clear why you would pass a gridView to such a static method, but you can.
I mean, in code it would be better to have say all your helper routines in a static class, and thus in code you could and would do this:
Say, on page load, fill out the grid view using that static class, like this:
Say my gv is this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" cssclass="table" >
<Columns>
<asp:BoundField DataField="Fighter" HeaderText="Fighter" />
<asp:BoundField DataField="Engine" HeaderText="Engine" />
<asp:BoundField DataField="Thrust" HeaderText="Thrust" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:ImageField DataImageUrlField="ImagePath" HeaderText="Profile Pic"
ControlStyle-Width="150px" />
</Columns>
</asp:GridView>
So, say on page load I do this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = General.MyRst("SELECT * FROM Fighters");
GridView1.DataBind();
}
}
So, we get this:
So, in above, I used the static class General.MyRst (and that static class is bunch of general code routines that are rather handy).
Now, I suppose I could setup that static class to take a GridView as a parameter, say like this:
General.MyRst(GridView1, "SELECT * FROM Fighters";
Gee, saved one line of code. So the above static class is now loading up (manuplaiting the GV).
so it is VERY easy to have a static method to load or do whatever to a GV.
However, you are confusing that of say the above simple static method that loads up and manipulating the GV as opposed to calling a web method to do the same thing. That is a VAST VAST different issue and VAST VAST different goal. We don't want to confuse the above simple and easy demonstration of a static method manipulating a GV with that of calling a web method - they are VAST VAST different issues and goals here.
But then again, I just built a method that is now tied to the GridView type and class. With above, MyRst returns a data table - I can use it for quite much any combo box, listview, gridView - it don't matter.
But, if you going to make a web method call, that occurs from the client side page, and how do you propose to pass the GridView object? You don't have use of the GV object client side, and you don't have a post-back, so the class instance of GV does not exist at this point in time.
And if you going to do this from the web page class, such as the above one line static class that "manipulates" the GV?
You have to pass that GridView from the web page class - code behind. And any ajax call to the current page does not have any of the controls, or even use of the current web page class (to get at and use controls).
So, any static class that uses say the GV? It will have to be called from that web page - which is not a static class.
And while you CAN add static web methods to the current web page?
Keep in mind this:
Any web method, INCLUDING ones on the current web page will also be static, and do NOT have use of controls on the current page.
I suppose you could have the web method call return the rendered gridview, and inject that into the page, but I fail to see the advantage here.
So, the problem here is that both web methods to you say add to the current page - they are also static, and don't have use of any control on the current page. And even a static class - it also does not have use of the web page. and you not done a post back, so you still in hot water.
It not clear what you final goal here is, but I fail to see how attempting to use a static web method going to help you fill a gridview when that gridview is a server side object, and one you do NOT have use of until such time you do a post-back.
if the goal is to avoid a post-back? Then I would return json data, and use a client side grid. On the other hand, it is VERY easy to simple drop in a update-panel, and load up the grid that way, and you not suffer a full page post-back. And in most cases, you can (and should) say turn off view state for that GV to reduce the size of the grid re-load.
You can try a working grid example - I put the grid inside of a update panel, and thus when you edit values, the response time is near instant. But MORE important I fired up the browser tools, and to pop the editor in that GV - the size is a VERY tiny 7k in size.
As a result?
I used plain jane code behind, but get no browser re-plots, and response time is absolute instant. Absolute instant response time, and no messy browser re-loads should be your goal here. And that goal in most cases can be achieved without having to resort to a ajax call to load up that grid.
Try this working grid edit example here - try clicking on edit - use save button. I did not have to wire up a bunch of ajax calls, and the only js code I have was using a jquery.UI dialog to pop the div for editing - but the div is filled with code behind.
http://www.kallal.ca/WebSite11/WebForm2
Given the absolute instant response time of above? Then you can avoid a boatload of work, avoid world poverty, and not have to resort to ajax calls when working with a gridview.
All you should care about as a developer is that you not doing huge post-backs, and your not having to write a lot of code for this goal. So, you want fast, you want instant response, and you don't want or need much of any client side code to achieve this goal.
so, "WITH" a static method, you can manipulate a GV. But you can't FROM a static method. Well, I suppose you could if you put the GV into session, since a static method can use session.
Related
I have a single-page site that has an UpdatePanel. Within that UpdatePanel, there are UserControls that are dynamically loaded.
All linking between 'pages' (which are just UserControls) is done by using a WebMethod that changes a Session variable that stores the UserControl to load. The page reloads, with a new UserControl, and everything works great!
The downside to this methodology, however, is that I'm aware that Session variables don't scale well. Too many of them kicking around is not a good thing, so I've heard. I've unsuccessfully attempted to use different methods but not have been able to succeed. I'm looking to set the UserControl to load very early in the Page Lifecycle.
I've tried HttpContext.Current.Items, UserControl public properties and even UserControl HTML injection. It's just a big mess.
Is there a best practice for this type of scenario? Any helpful links or suggestions?
All is much appreciated.
Clarity update
I'm looking to change the UserControl to be loaded by the C# code-behind file through either jQuery method calls or a Webmethod. Session variables work, but don't scale.
I would use localStorage, you can store lots of information like this
localStorage.setItem('var', 'data');
and get the data back like this
var data = localStorage.getItem('var');
I have html label contol without runat="server"
Does it possible to get inner text from code behind c#?
Label:
<label id="lblClanName">Text Here</label>
Thanks
Every time an ASP.Net page is posted back to the server it is recreated from scratch using the custom code contained in the page (such as calls to a database), the HTTP post/get collections (which include ViewState), any custom data in Application, Cache, Session, static objects, etc.
If the value does not exist in any of those locations, the server doesn't have access to it. A common trick to pass data from the client is to simply use a hidden field. If you want something more elegant, you can use asynchronous AJAX to send/receive data from the server.
Or in this case, you could just add runat="server" to an asp:Label. ViewState will maintain the value between postbacks, though it will not reflect changes made client-side unless (once again) the data is somehow passed back to the server.
Note that ViewState is typically a bad thing because it essentially doubles the size of your data (or more) and (in my opinion) encourages sloppy design.
i don't think you can do it.either you can use js get the lable,and call js method from code behind
Short answer: no.
To access this from your code-behind, you will minimally need to add runat="server" to your label. This will allow you to access it using Page.FindControl(String).
The preferred approach, if you are able to modify the front-end code, would be to use an <asp:Label />. This will allow you easy access by just using the control's ID in the code-behind, specifically its Text property.
Do you want to know how to parse a string value for the inner html, or do you expect your web page do have text written to the label at runtime?
string labelHtml = "<label id="lblClanName">Text Here</label>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(labelHtml);
string innerText = doc.DocumentElement.InnerText;
Why do you need the text between a label, is this for a live web page? This sound like a bad design more than a requirement.
I am creating a web application for my company that needs to deal with form processing and database manipulation. The application is implemented using .NET Framework 3.5 using C# and Visual Studio 2008 as the IDE and Microsoft SQL Server 2005 as the database.
Here is my problem:
I have a lot of forms
But my boss only want me to create a single page for the database
processing (easier to extend in the future)
I figured out the only way to solve this problem is by having only 1 .aspx file (that contains everything about the database) and having it invoked as a pop up window everytime a forms need to deal with the database.
Here is another problem of mine:
Due to stateless nature of HTTP, I am unable to process and pass
variable between 2 different windows.
I managed to create certain Javascript functions and have the
variable transferred on display, however it can only pass a variable
that is the primary key in the table. To process other columns in
the table is possible but as the consequence I have to write a very
long inline script in my .aspx page and after it is compiled people
can easily view how to access my company database easily. Hence, I
don't favor this (beside to deal with 1 form, I need to create a
long code already, imagine if i have more than 1000 forms!)
So there are two ways you guys can help me:
Suggest another way other than popping up a new window for my
problem, maybe even advise on how it's implemented.
If you think popping up is the solution, you mind to share some
snippets that can help me figure out the variable passing between
two different windows. I can use some advise especially from some
Javascript expert on this :).
Note: Solution must be workable in ASP.NET Framework 3.5 and tested using IE browser version: 8.
P.S: This is a short explanation about my application flow
Let's say I entered data about a product (it has few properties id, name, price, etc) into the database
Later on somehow I want to edit one or few properties of that product, so I have to launch a form which called "editor.aspx"
Instead of entering the product id (which is the primary key) into the form (and edit the data based on the entered product id) and risking to miscalculately edit the correct data, I provide a small button in the form (let's name it btSearch), that will launch a new popup window which contains the gridview of the database of all product (with selection enabled)
Now I just need to browse through the gridview, select a particular row, it will close the popup and I expect to see few data from that row appeared on my original page (in the textboxes/labels)
I hope my explanation above clears the air, thank you.
I recently wrote something like that: A database handler as aspx file. But i invoked it by using ajax / jquery.
When my aspx file is done, i write something to the response stream, some code, a json string, what ever.
Example:
$.post("yourdatabasehandler.aspx", { name: "John", lastname: "Smith" }, function(data) {
alert("Response from page: " + data);
});
In that example, name and lastname are values that are posted to your site. You can access them like that:
string name = Request.Params["name"]
// Do your database , validation and whatever logic here
Response.Write("Cool dude");
The above javascript will alert "Cool dude" after your databasehandler is done. Inside your javascript you can react to the response how ever you want - For example reload a page.
Hope that helps? Regards
"1. Due to stateless nature of HTTP, I am unable to process and pass
variable between 2 different windows."
You very wrong with this comment to start with, trying MSDN and ASP.Net "How to pass values between ASP.Net Web pages". Passing between Windows only requires a little bit more thought and possibly a little Javascript to refresh a parent windows or cause a postback on a shild window etc.
If you're using a popup window, you can always use QueryStrings to pass a value going to your popup.
window.open("popup_page.aspx?id=" + id + "&name=" + name)
to access it in popup_page.aspx
string sID = Request.QueryString("id");
string sName = Request.QueryString("name");
Update: if you're using IE the this might help you.
function ShowPopup(strMessage)
{
var returnValue= window.showModalDialog("popup_page.aspx");
}
popup_page.aspx
<asp:Button ID="btnReturnValue" runat="server" Text="Proceed" OnClientClick="window.returnValue='some message';window.close();" />
Note: Please note this only works in IE, so I suggest consider using the followings instead:
jQuery
AjaxControlToolkit ModalPopup
I personally suggest the use of jQuery. :)
Thank's for all answers, comments. rates, and feedback. Just now I found a very helpful link here. Basically the answer is based on that particular code. I just need to alter some part.
<script language="javascript">
function GetRowValue(val)
{
window.opener.document.getElementById("ctl00_ContentPlaceHolder1_TextBox2").value = val;
// make sure you change the TextBoxId as respective to your creation
window.close();
}
</script>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
<Columns>
<!-- Reserve the code below, as after you configure data source you -->
<!-- will alter this code drastically therefore-->
<!--you have to make sure to paste this code -->
<!-- again inside this Gridview element once you configure your data source -->
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
<!-- This part must be reserved -->
</Columns>
Also remember to specify the connection string and the sql command in the datasource.
The rest just follow that tutorial and copy paste the code entirely.
I have two user controls that sit on a page which determines which should be displayed. The user controls generate some html that is passed into an asp:literal and subsequently manipulated via javascript. It is done this way due to the lack of a suitable control that I am allowed to use on the project.
When a user clicks a view change button, a WebMethod is called on the main page (the one that holds the controls) from the control's javascript. From here, a static method on the control is called. The control then needs to regenerate the html and place it into the asp:literal for the view change to be complete.
My problem is that I am in a static method on the control's page, and have no access to the non-static genorateHtml function. I have tried a singleton pattern with no success (this could have been due to improper implementation). Any ideas on how to make this call? THANKS!
I used to hit similar issues at with one of the projects i worked on. The solution we ended up adopting was implementation of System.Web.UI.ICallbackEventHandler with partial rendering to return just the needed content depending on arguments. ICallbackEventHandler runs in the page lifecycle.
The only trouble we had then was performance issues relative to implementation which posts back the whole form instead of just the arguments you want.
Maybe the best way for you would be through this method in which they render the control from a static method. That would probably suit your needs.
Hope this helps!
I need to expose some input fields based on what properties I find for particular types in an assembly.
I'm not sure how common an approach like that is. Perhaps there are easier ways. Maybe on the client side instead of server.
If anyone knows of a good way of doing something like this, I would appreciate the help.
Create input controls accordingly and simple add control to some div container? I'm not sure if it would be more complex than that.
I'll need to somehow add css classes to the controls as I build them so they get placed nicely; that might get tricky.
This all sounds like standard asp.net development. Any good tutorial should be able to help you. For the asp server controls, you use the CssClass property to set the class for the control.
Here is the asp.net tutorial from the W3C Schools.
I assume you will use reflection to figure out what properties entity has, then you would based on the type of the property create an input field. You would have to dynamically create control to handle input in code behind. Make sure you give that control and id. You will have to recreate these controls on the post back. This looks to me like dynamic property editor. There might be some free ones, google for it.
If the UI doesn't have to be completely dynamic you could include all the controls in the markup with any optional ones set to Visible="false". Then, selectively enable the appropriate controls in your code-behind. For example:
Default.aspx
<asp:Button ID="EvenButton" runat="server" Text="Even" Visible="false" />
<asp:Button ID="OddButton" runat="server" Text="Odd" Visible="false" />
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
String msg = "A message to count";
if (msg.Length % 2 == 0)
{
// Enable the Even Button
EvenButton.Visible = true;
}
else
{
OddButton.Visible = true;
}
}
The advantage of this method is that you can lay things out with the appropriate CSS easily in the markup. If, on the other hand, your UI is much more dynamic than this, you'll probably have to resort to dynamically creating controls in the code-behind and adding them to the page via calls to Controls.Add(). This way, however, is harder to layout. And you have to deal with things like re-wiring any event handlers on each postback.
Hope that helps.
I ended up leveraging jQuery.
I laid out a simple markup with the basic layout I would need.
For creating controls dynamically, I did it all in javascript using jQuery methods.
This of course requires that you return some data set to the UI intelligently enough to render it.