Problem
I have some pages that need dynamic data from website to generate output to users.
A simple solution is an aspx(php, ...) page to generate data and create another html page serving as GUI retrieving data from first page and showing it to users. in this method I can call my GUI page for example form1.aspx and my data page form1.json.aspx.
although I personally like this method, it is not suitable when creating components for it.
Another method that currently I'm using is using same GUI page call itself with a querystring to retrieve data. this page should check for that query string and if it exists, only generate data and remove everything else from page. As an example for this method if I call my page form1.aspx, to retrieve data, I need to call it like form1.aspx?JSON
Here is an example of what I'm doing:
protected void Page_Load(object sender, EventArgs e) {
if (Request.QueryString.ToString().IndexOf("JSON") == 0){
this.Controls.Clear();
Response.Clear();
// send pure data to client
} else {
// render page as GUI
}
}
However this method becomes too messy if I add master page and/or inherit my page from some template page. Master pages can only removed in Page_PreInit and that adds another extra method.
Security controls cause another problem, if user leaves page open for long time until session expires any attempt to retrieve data will fail cause security module will redirect the request to login page.
Next problem is I cannot consolidate my component in package because it needs modification in page (removing master page, clearing page components ...).
What I'm looking for:
1- I'm looking for a solution that I can call my page and get pure data (JSON or XML format) and doing so run a server side method that generates data, so I don't have to worry about what another designer puts in their master page or template.
2- I think it is possible to use axd extension to do this but I don't have a clue about it and couldn't find a helping document either.
3- Is there any better way of doing this. any suggestion or solution to improve this much appreciated.
Page methods. Check this article: http://weblogs.asp.net/craigshoemaker/archive/2008/09/29/using-jquery-to-call-asp-net-ajax-page-methods.aspx or http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
WCF JSON service: http://www.codeproject.com/Articles/327420/WCF-REST-Service-with-JSON
Other ways of doing is using an HTTP Handler. Implement IHttpHandler interface and register your implementation in your Web.config file. Later call it using jQuery ($.get / $.post):
http://msdn.microsoft.com/en-us/library/46c5ddfy.aspx
EDIT
As OP pointed out, in order to access session state in a page method you should use WebMethodAttribute this way:
[WebMethod(EnableSession = true)]
I think you can use webservice instead of aspx page to return a JSON or XML string and then the caller page (any aspx page) will response after process is success.
So with this webservice, any third party page will have access to your server side method.
To create a webservice pls Check this link: Create and use Asp.net web service basic
Regards
Related
I have a content page connected to a master page. I can access an element on the master page and modify it directly from the content page .cs file by calling a method on the site master. (this is probably the most standard bug people have in this type of area)
My problem is that I wanted to extend this functionality to update the site master page from an AJAX request as well. The ajax file calls a different page which in turns starts an instance of the logic layer which I use for all the calculations and connections. What I am trying to do is access the sitemaster directly from the logic layer (only a .cs file).
My current code is this:
SiteMaster sm = new SiteMaster();
sm.MyMethod("param1", "param2");
This successfully accesses the method called "MyMethod" in the site master but inside this method I have this code:
mySpan.InnerText = "this is a test";
which doesn't work because I get the "Object refernce not set to an instance of an object...." error. This is because mySpan is NULL. If I call it using this.mySpan.InnerText though, if I hover over "this" then I can see the ID "mySpan".
Does anyone know how I can get around this problem? Every search I have made is regarding people who want to access the elements from the content page which already works for me.
I believe you've got a misunderstanding here. If I understand correctly you've got a page with a MasterPage. On that aspx page you're doing an ajax call (perhaps to a WebService) which does something like:
[WebMethod]
public void UpdateText(string message)
{
var master = new SiteMaster();
master.mySpan.Text = message;
}
There are a couple of things wrong here.
When you use this approach is an aspx page you're updating that Page's master. For example:
public void OnSomeRandomButtonClick(object sender, EventArgs e)
{
((SiteMaster)this.Page.Master).mySpan.Text = "Some Text";
}
What you're doing here is updating the span on the master page before it's being sent to your browser. The other subtly is that you're not creating a new SiteMaster, you're using the Page's existing Master and casting it to a SiteMaster.
There are a couple of reasons you can't do this with ajax:
A webservice doesn't have a MasterPage
By the time you send an ajax request your Master page has already been created and sent to the browser.
So your question becomes how do we update a span in the Master without posting back to the server?
Lets look at the html which is actually on your box, it will look something like this:
<html>
<head>
<title>My Awesome Page</title>
</head>
<body>
<h1>This is my Awesome Website</h1>
<span id="mySpan">I'm sure you'll like it</span>
<div>
<p>Page Content</p>
<div>
</body>
</html>
Lets assume that everything here is generated by the master and only the <p>Page Content</p> is your aspx page (There will also be loads of ASP.NET junk added, we'll ignore that for the time being).
What you want to do is update the text in mySpan without posting back to the server. You can do this via the javascript - don't get ajax involved at all!
I'm going to assume you're using jQuery (mostly because I'm more familiar with it that plain old JS). You've got the ID of your span ("mySpan") so the rest is easy:
$('#mySpan').html('This is the updated message');
You can put this in either a click or a page load.
No. You can not simply construct an ASP.NET page and use its state.
ASP.NET pages (and controls and Master pages) are being constructed and initialized from inside the ASP.NET engine based on the Markup provided for them. There is for example no initialization for mySpan inside the codeBehind of your master page, that will be constructed when the code generated based on the Markup is invoked based on a user request.
So you define this in your class:
protected HtmlGenericControl mySpan;
But the ASP.NET engine will compile this markup
<span id="mySpan" style="color:green"></span>
to this code:
this.mySpan = new HtmlGenericControl();
this.mySpan.Style.Add("color", "green);
and that is why you can use this object inside your code.
So if you want to use a property of your Master page from your Business layer, you have so many choices. On of the fastest one to implement is to make your Logic class singleton inside the Session scope, store the value you want to use inside the master page into that singleton object and then read that value from the master Page. This is an example of what you should do, of course it is rough.
class Logic
{
public static Logic Instance
{
get
{
if (HttpContext.Current.Session["LogicInstance"] == null)
HttpContext.Current.Session["LogicInstance"] = new Logic();
return (Logic) HttpContext.Current.Session["LogicInstance"];
}
}
public string TextForSpan {get;}
// The rest of your implementation
}
Instead of the code to assign the inner text, write:
Logic.Instance.TextForSpan = "This is my text";
And inside your master page:
this.mySpan.InnerText = Logic.Instance.TextForSpan;
I would like to know which is the best way to do this: I have a form using ASP that is being validated firstly on client-side with jQuery. In this form I have a FileUpload control to upload an Excel file and the validation of this control is being made on server-side to check the file type, valid data, valid structure, etc... I really need to make the file validation on server-side to be as secure as possible and I don't want to use ActiveX.
The problem is that, when the server-side validation returns an error, the previously inserted data in the form is lost due to the postback.
Is there a way to make client-side validation, then after this is done, make the server-side validation and on the postback don't lose the sent data?
I think the best way to do that is to get old values of field at Page_Load.
All you have to is check if page is postback.
if (Page.IsPostBack)
{
YourTextBox.Attributes.Add("Value", YourTextBox.Text);
}
Hope this help you.
Try adding a CustomValidator to you form that will call the FileUpload.SaveAs() method and that will validate the uploaded file.
For example:
protected void ValidateCstm_ServerValidate(object source, ServerValidateEventArgs args)
{
//Upload the file
fileUpload1.SaveAs(....
.....
.....
//Validate the fileUpload
.....
//If the fileUpload is invalid
args.IsValid = false;
}
I hope that this helps.
Have you considered using AJAX for the file validation, thus avoiding a full post back altogether? There are several AJAX-based file upload widgets 'out there' that might serve your purposes...
just when you encountered any error on server side , set all your form post data in some session variable and redirect to the form and show the form filled up with this session data.
Alternatively you can use jQuery File Upload component. It does not require post backs. It needs server to handle HTTP GET, POST and DELETE and return JSON. You can use ASHX for this. This way your server side validation will not interfere with post backs.
Or any viable workaround.
So, imagine a Master page that implements IFooMaster with a method ShowFancyMessagePopupTheBusinessCantLiveWithout(string message);
I am in a page that inherits this master page. Upon a checkbox being unchecekd, I want to show a message to the user that if they save it, they can't re-check the checkbox without some admin action.
I've been given feedback that I can't just use an alert('message'); in javascript because they want the consistent look of these messages.
Next, I tried to make an ajax call via PageMethods (as that's what everything else in this codebase uses) to show a message. My problem lies in this method being static.
[WebMethod]
public static void ShowSuperImportantMessage()
{
if(!checkboxICareAbout.Checked)
((IFooMaster)Master).ShowFancyMessagePopupTheBusinessCantLiveWithout("If you uncheck that thing, you can't recheck it.");
}
Since ShowSuperImportantMessage() is static, I can't access Master from within.
The method on the master page looks more or less like this:
public void ShowFancyMessagePopupTheBusinessCantLiveWithout(string message)
{
lblGenericMessage.Text = message;
btnGenericMessageOK.Focus();
upGenericMessage.Update();
mpeGenericMessage.Show();
}
mpeGenericMessage is an ajaxtoolkit:ModalPopupExtender.
upGenericMessage is an update panel.
The other 2 are obvious.
Any ideas? Can I do some jQuery kung-fu to show that stuff? I tried, but the solution complained that the controls I tried to refer to by ClientID didn't resolve since they were on the Master page.
quick edit: Before anyone tells me the architecture is a problem, or I shouldn't have put such a thing on a master page, or w/e...
I know the situation is not ideal, but I this is inherited code, and I can't drop it all and rewrite half of their web stack.
Try something like this (untested):
((IFooMaster) ((Page)HttpContext.Current.Handler).Master)
It appears this doesn't work - Master isn't hooked up when the PageMethod is called (makes sense).
So, instead, create an empty page using the same master page. Have that page accept either a POST or GET with whatever parameters you need to pass to your master-page method. Have the Page_Load extract the parameters and call the method. It should then use Response.Write to return a result (and remember to change the Content-Type). Have your client-side code call the page and get the result.
Did you try something like window.top before the ClientID?
Per comments
You don't need to hardcode ClientID. Since your js is in page, try something along the following lines....
window.top.document.getElementById( "<%= yourelement.ClientID %>" ).Whatever();
Sorry to take so long to respond/answer.
I'm not proud of this at all, mind you, but the eventual solution was to hardcode the client IDs into the jQuery that pulled up the modal dialog on the master page.
Like I said, I'm not proud of this dirty, dirty fix. However, the consolation is that, since it's on the master page, there isn't really any naming container above it. As such, it's much less likely to run into problems with the clientID changing.
I have a javascript code which builds a link with 2 params.
Now, I know how to post these params using the address, but I don't want to use it.
I've tried using cookies for posting the params, but somehow I can't read them on the server side.
this is the client side code
document.cookie="name="+"value";
this is the server side reading code
string s = Response.Cookies[cookieName].Value;
Can you hep me out?
Create a mini form (not an asp.NET web form, just a simple one) with two input type hidden fields named as your parameters. After that create a link or button an tie the onclick event of it to a javascript function (example: onclick="javascript:postIt();").
Then when user clicks the button or the link the function will replace the value of those parameter something like:
document.miniform.parameter1.value = yourvalue1;
document.miniform.parameter1.value = yourvalue2;
document.miniform.submit();
To get the parameters back into code use Request.form("parameter1") and so on...
You can use an Ajax Request to post your data to an ASP.NET form.
To post data to any page, you HAVE TO use the path to that page. As for your problem with setting the cookies, they can only be used by a page in the same domain.
Are you doing an HTTP Post? You could post these values inside a form field. I'd use a hidden input field. You can add one in your markup or add one via the javascript.
Your other option is to use some sort of Ajax and pass JSON or XML in the body of the post.
Cookies are meant to save data client side accross pages and/or sessions.
I have a text string value that I'd like to persist from one web page to another without using query strings or the session/view states. I've been trying to get the ASP http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx">HiddenField control to pass information from one web form to a different form.
All the hiddenfield control examples that I've seen is to preserve round trips from the client to the server for the same form.
Is there way for a form to access the ASP controls (and their values) from the previously-rendered form? Or is the initial form simply disposed of in memory by the time the second form executes it's OnLoad method?
Quick answer is no. As others have noted, you can use Server.Transfer and then you can - however this is to be used with caution. It is a "server side redirect" eg.
Your user is on http://mysite.com/Page1.aspx they click a button and you perform a Server.Transfer("Page2.aspx"). Page2.aspx will be rendered in their browser, but the URL will still be Page1.aspx, this can cause confusion and mess up back/forward navigation.
Personally I would only use Server.Transfer as a last resort - in the world of the web, sharing data across pages generally means you need to use a storage mechanism; Cookie, QueryString, Session, Database - take your pick.
You can't get the previous page fields with Response.Redirect.
You can with cross page posting :
if (Page.PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.Text;
}
}
If both pages live in the same application you can use Server.Transfer:
firstpage.aspx:
protected void Page_Load(object sender, EventArgs e)
{
Server.Transfer("~/secondpage.aspx");
}
secondpage.aspx:
protected void Page_Load(object sender, EventArgs e)
{
Page previousPage = (Page) HttpContext.Current.PreviousHandler;
Label previousPageControl = (Label) previousPage.FindControl("theLabel");
label.Text =previousPageControl.Text;
}
A somewhat better solution would be implementing an interface on your first page where you expose properties for the values needed by the second page.
I would presume that the Response.Redirect() sends a Location: HTTP header to do a redirect.
As HTTP is stateless, I'd also presume that these variables are inaccessible.
There are however, solutions.
Print a form with hidden fields, and use javascript to submit it
Redirect in the code internally (load up the thing it needs to get to manually)
Store the data in some temporary database table somewhere, and pass along a unique ID
However, from my experience, I can't understand why you might need to do this (other than re-submitting a form after a user authentication - which hopefully you should be able to use method 2 for
Remember, a Response.Redirect instructs the browser to issue another request to the server. So far as the server is concerned, this next request is indistinguishable from any other incoming request. It's certainly not connected to a previous form in any way.
Could you explain your aversion to storage in the session, so we can propose some viable alternatives?