accessing methods of page when accessing page with a page method - c#

I have a code behind file of an aspx file that looks like this:
public partial class Pages_MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
.....
}
protected int MyMethod()
{
.....
}
[WebMethod]
public static int MyPageMethod()
{
int x = MyMethod();
return x;
}
}
When I'm sending an ajax POST to MyPageMethod, I can't access MyMethod. What's the way around this issue.
Thanks for your suggestions.

MyMethod will also need to be static.
Think about what your trying to do here -
MyMethod belongs to a specific instance of a class.
MyPageMethod belongs to the class itself.
If your running code inside MyPageMethod, how could you possibly know how to call methods on some other instance of the object. The instance methods may as well not exist at that point in code.
If you are trying to mutate some portion of the page's data from javascript, you have a deep misunderstanding of how asp.net pages work.
At the point javascript is running in the browser, your page object is gone. The server finished the page load and discarded it. On the next post back it will create a new instance, and run through the page life cycle once again.
If you need to access page level state, you will have to store it in a place that is acceptable between post backs, the Session object for instance, with System.Web.HttpContext.Current

WebMethods are static methods because they don't get a full Page.
They can only call other static methods

Related

External class to run code on another page

I want to create a reference for button click event which happens on another page in UWP project.
Page one (witch button):
private void Button_ItemClick(object sender, ItemClickEventArgs e)
{
// some code to reference to class
}
Class (in external file)
public static void DoSomething()
{
// Do something on Page 2 or run void on page 2
}
If the method is static, you can call it without an instance of the class. Suppose the method is defined in class OtherPage. You could then just do:
private void Button_ItemClick(object sender, ItemClickEventArgs e)
{
OtherPage.DoSomething();
}
In case the method is not static, you cannot easily do that, because there is only one Page instance in memory at a given time, when you have just one navigation Frame. It would make sense to put the method into a service class that would have a singleton instance and you could call it from anywhere. You can use MVVM framework like MvvmLight or MvvmCross to make this easier. These frameworks also maintain navigation stack of pages and their view models so you can potentially access view model instances in the navigation backstack.

Store information across postback with static variable

I'm new to ASP.NET and C#. I have a web form with a static list like this:
private static List<Book> listBook = new List<Book>();
Since the server destroys everything after sending back to client plain HTML, so why whenever I add a new book to the listBook(via checkboxes), it stores info across post back(in a single page)? First I thought it was viewstate but clearly viewstate only stores ASP.NET Control info. Please help me, Thanks in advance!
public partial class TestSortBook : System.Web.UI.Page
{
private static OBMDbContext context = new OBMDbContext();
BookBL bookBL = new BookBL(context);
GenreBL genreBL = new GenreBL(context);
private static List<Genre> listGenre = new List<Genre>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Book> listBook = bookBL.FindAllBooks();
PopulateGridView(listBook);
//PopulateGridView(bookBL.SortBookByPriceAscend(listBook) );
PopulateListView(genreBL.FindAllGenres());
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
HiddenField hf = (HiddenField)cb.FindControl("HiddenField1");
int genreID = Convert.ToInt16(hf.Value);
listGenre.Add(genreBL.FindGenre(genreID));
Response.Write("Nothing");
}
}
Let me explain the code above. There's a listview which has a checkbox and a hidden field in each listview item. Whenever I click a checkbox, it add a new genre to my listGenre and save info across postback.
Since the server destroys everything after sending back to client plain HTML
That's not true at all. Each postback results in a new class instance being created to handle the response for that request. Since you have a static field, its data will persist between requests.
That said, you cannot rely on every single request having access to the same variable with this method; if you have multiple web servers handling responses, they would each have their own static variable. This makes static fields useful for caching content in some instances, but not as the canonical source of data (generally speaking).
where does the static variable store info across postback?
In memory, as any other variable.
You must understand that each page on Asp.net relies in a class, it's not like php or other scripted languages, your site is a program (technically speaking it's an assembly loaded in an AppDomain under the IIS process :P), because that you have an application pool on which you configure how that "program" will run (basically each pool is an isolated AppDomain), so, while the server doesn't purges these application pools your site pages classes will be alive , and thus any static variable will persist on memory.
Have you considered using the Browser Local storage to store stuff for each user.
depending on what you are storing and how you plan to use it, it might be the best option

Calling a method of the ASPX page from Web Service

I have a simple Web Service with one method. (This method calling from another application)
In this method I need to call ASPX page of sided site - not html code, but method of this page.
Can anyone ask, how can I do this?
It is generally a good idea to have shared/reusable code stored separately from both the web service and the ASPX page so that any number of dependents may access it.
But to answer your question specifically:
I'll assume that the web service class is able to reference the ASPX page class (.aspx.cs or aspx.vb).
The example below shows two ways of accomplishing what you're asking. You can either instantiate your Page class and use the method just as you would any other normal class, or if the method is static, use it as is without instantiating your Page class.
Example:
public class MyAspxPage : Page
{
private Object _myObj = new object();
public object GetObject()
{
return _myObj;
}
public static object GetAnObject()
{
return new object();
}
}
public class MyWebService : WebService
{
public void MyWebServiceMethod1()
{
MyAspxPage page = new MyAspxPage();
object result = page.GetObject();
}
public void MyWebServiceMethod2()
{
object result = MyAspxPage.GetAnObject();
}
}
you don't want to be sharing code in aspx pages. You should create a project of type class library in your solution. Put your code that you want to be common code called from aspx pages and web services into the class project in a class.

Number of objects created by a page in asp.net

I have a calculation class file where I am doing something. I made an object x of the calculation class in .cs file of aspx and called it in aspx using server tag.
Now I am getting hits for that page.
Is that page is going to use the a single object for that class or for every hit will it create a new object?
Is this a good practice of doing coding?
calculation.cs
using system;
public calculation()
{
//some decelerations
}
public string getProduct()
{
return (A*B*C).toString();
}
page.aspx.cs
public calculation cal = new calculation();
page.aspx
<%# cal.getProduct()%>
It is completely dependent upon how you have instantiated the object.
If it's a singleton with a static variable scope then it will be created once for each app domain. If the app recycles then it will be created again. ASP .NET Singleton
If it's a singleton that's stored in the HttpContext, then it will be created once per request. See example here of how to do this: http://dotnetslackers.com/community/blogs/simoneb/archive/2006/08/21/The-ASP.NET-Singleton_2D00_per_2D00_Request-pattern.aspx
If it's a regular variable, then it will be created once every time that page code is called, even it is on the same request.

How to work around Response / Server which does not exist in the context?

I have this C# ASP.NET 4 website.
I would like to have a general method in a class which will include a Response.Redirect or Server.Transfer in it to a specific page.
Both names, Response and Server, does not exist in the context.
How to work this around?
as for the comment by #Maess, please consider something like this (edited):
ASPX:
<asp:Button onclick="MyClass.btnRedirect_Click" ID="btnMyButton" Text="MyButtonText" runat="server" />
Code behind:
public static void btnRedirect_Click(object sender, EventArgs e)
{
Response.Redirect("~/SomePage.aspx");
}
You'll find these as properties within HttpContext.Current
You can use System.Web.HttpContext.Current, but be careful. If there is no HTTP context at the time these methods are called you will get an exception.
It is probably safer to have these classes either require an HttpContext in the constructor or have the methods that require an HttpContext to have them in the method signature.
For instance, maybe you have a class which needs to redirect as you mentioned. Your method signature might look like this: public void CustomRedirect(HttpContext context) then within the body of your signature you would do something like this: context.Response.Redirect("..."). Basically, you make the class or method dependent upon having an HttpContext.
Don't directly reference anything involving the HTTP/IIS stack if you're ever going to be called outside of it.
Your best bet is probably to have your class or method accept either a delegate or an object that implements an interface provided by the calling code. When you're ready to redirect, call that delegate/interface method with the URI (or enough information to construct it) and then the calling code can respond with a server.transfer, a response.redirect or a passing unit test.
public static void ButtonRedirect()
{
MyClass foo = new MyClass(delegate(string s) { Server.Transfer(s); });
foo.DoThings();
}
public class MyClass
{
private Action<string> redirector;
public MyClass(Action<string> redirectAction)
{
redirector = redirectAction;
}
public void DoThings()
{
//Doing stuff
//Aha! this should redirect
redirector("/go/to/here");
}
}

Categories