im sending a value from one page in aspx to another page as shown below.
window.location="test1.aspx?id=1"
how to access this value in codebehind or global.asax?
You could retrieve the id parameter from the Request object in your code behind:
protected void Page_Load(object sender, EventArgs e)
{
string id = Request["id"];
// do something with the id
}
Also you will have to fix your javascript because the url you are assigning is invalid. You have an extra + character that should be removed:
window.location.href = 'test1.aspx?id=1';
Leave the + sign out and use the Request.QueryString object.
window.location="test1.aspx?id=1"
string v = Request.QueryString["id"];
Related
I have a c# method which stores data to sql server. This function is called from an Onlick and i pass the parametres using CommandArgument. Like this.
<asp:LinkButton runat="server" onClick="save" CommandArgument='<%# Eval("post_id").ToString() + "," + Eval("user_id").ToString()%>'></asp:LinkButton>
This is the c# method
protected void vote(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
string arguments = lb.CommandArgument;
string[] args = arguments.Split(',');
string post = args[0];
string user = args[1];
.............
}
All i want to do is to call the c# method using ajax because i dont want the page to be refreshed, but i cant call that function passing CommandArgument. I want to use CommandArgument because i dont want the c# method to have other parametres than object sender and EventArgs e
Try this:
<asp:LinkButton runat="server" onClick="save" CommandArgument='<%# Eval("post_id").ToString() + "," + Eval("user_id").ToString()%>'></asp:LinkButton>
In script tag:
$("#<%= myVote.ClientID %>").click();
Attempt 2:
In script tag:
var func = $("#<%= myVote.ClientID %>").attr('OnClick');
eval(func);
The idea is that Asp.Net WebForms uses JS to do postback to backend, a function generated called __doPostBack, the idea is to use the same function and call it, or just inspect the generated HTML of the page and get the value of ,as I remember, OnClick attribute of the button, and use it.
This may help also:
How to use __doPostBack()
In my project, there is a asp button with a C# button_Onclick handler. The problem is when you click the button on html, the event will be kept by browser. For example, the event will be sent if you refresh the browser..
I have tried add a return; to the end of the button_Onclick handler and a JavaScript for thebutton_Onclick handler to call, but all fail.
asp:
<asp:Button ID="btnSubmit" runat="server" Text="Save" />
C#:
protected void btnSubmit_Click(object sender, EventArgs e)
{
.......
return;
}
Assuming your code makes a POST request when clicking the button, this is how browsers behave and should behave on refresh. They must send the submitted data again to the server. If you want to avoid this, then in your submit handler method you should do a redirect to another URL after doing whatever your handler does.
For example if form.asp displays your form, then in your handler you can redirect to form.asp?message=thankyou (notice the different URL), then in case of refresh, your form will not be sent again by the browser to the server.
Also, best would be to use a 303 redirect.
You should redirect to another page to avoid this.But In case if you want to stay on the workaround is as follows.
In your pageload_Event capture the dateTime.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["update"]=Server.UrlEncode(System.DateTime.Now.ToString());
}
}
In the Page_PreRender Event Copy the sessionVariable to ViewState Variable.You can refer following to get a clear understanding on Page Life cycle. "http://www.codeproject.com/Articles/667308/ASP-NET-Page-Life-Cycle-Events"
public void Page_PreRender(object obj, EventArgs e)
{
ViewState["update"] = Session["update"];
}
Now in your button on click event compare the ViewState ans session variable.Allow into the block if both the values are equal.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Session["update"].ToString() == ViewState["update"].ToString())
{
try
{
-----------Your Logic
}
finally
{
Session["update"]=Server.UrlEncode(System.DateTime.Now.ToString());
}
}
}
i have a page where in the form load i initialize a server side variable with value and i want to render that value in js section. i am working with asp.net webform apps.
my server side page load code
string errblankEmail ="";
protected void Page_Load(object sender, EventArgs e)
{
errblankEmail ="Hello World";
}
if (str == '') {
alert('<% =errblankEmail %>');
}
when i run the page then i am getting error message like
CS0103: The name 'errblankEmail' does not exist in the current context
and i also saw that my page_load is not getting called because i set break point there.
so guide me how to fix this problem. thanks
You have to make the variable public in order to access it.
public string errblankEmail ="";
I want to pass data from one user control to another one, but i've tried several things to do it, and non of them worked, such as sessionStorage in JS, Session in ASPX, cookies in both of them.
This data is dynamic so I don't now how to transfer it, to the other user control.
I even tried to put aspx code in the javascript function (then when I click in the button it could trigger the code, but it doesn't work as well).
This button i refereed above is written in a literal control.
JavaScript Functions
this function is the LoadUsers UserControl
function getID(ID) {
sessionStorage.setItem("userID", ID);
}
this function is in the Access UserControl
function catchIP() {
var ID = sessionStorage.getItem("userID");
$('#<%= value.ClientID %>').val(ID);
}
UserControls
Load Users:
...
string _str = "<a href'#lastAccess' css='btn btn-success' onclick='javascript:getID(" + _id[_contForeach] + "); catchID();'>Access</a>";
_loadUsers.Controls.Add(new LiteralControl(_str));
Access:
How can I get access to the ID in the JavaScript function and apply it without using Page_Load
To pass information between the server side code and the client side code (JavaScript) use ajax
Ajax
So using jquery, have something like this function:
$.get('getuserid.aspx', function(response) {
//Do something with return response
});
then in the code behind getuserid.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
Response.Expires = -1;
//required to keep the page from being cached on the client's browser
//set userid
Response.ContentType = "text/plain";
Response.Write(userid);
Response.End();
}
First of all, the only post (calling-multiple-dopostback-from-javascript) I found about this didn't help my problem, so I don't belive this post is a duplicate.
I have this JavaScript function in my ASPX webpage that includes a __doPostBack function:
function OpenSubTable(bolID, controlID) {
// code
__doPostBack('UpdatePanelSearch', bolID);
// more code
}
Works perfectly and I can get the value of bolID into my code behind like this:
protected void UpdatePanelSearch_Load(object sender, EventArgs e)
{
var bolID = Request["__EVENTARGUMENT"];
// code
}
The problem is, that I have to pass 2 different values through the postback. Are there any simple solutions to this? Obviously something like this doesn't work:
function OpenSubTable(bolID, controlID) {
// code
__doPostBack('UpdatePanelSearch', bolID, controlID); // not that simple, i'm afraid :(
// more code
}
Any help would be most welcome.
Regards,
Gunnar
You could pass the two values as one JSON string:
function OpenSubTable(bolID, controlID) {
__doPostBack('UpdatePanelSearch', JSON.stringify({ bolID: bolID, controlID: controlID}));
}
And then parse it on the server:
protected void UpdatePanelSearch_Load(object sender, EventArgs e)
{
SomeDTO deserializedArgs =
JsonConvert.DeserializeObject<SomeDTO>(Request["__EVENTARGUMENT"]);
var bolID = deserializedArgs.bolID;
var controlID = deserializedArgs.controlID;
}
public class SomeDTO
{
public string bolID { get; set; }
public string controlID { get; set; }
}
If you're using .Net >=4.0, I believe you can deserialize to a generic touple and avoid having to create SomeDTO. Edit: More information about deserializing to dynamic types.
Consider placing your data in server side hidden fields and then reading that data after your postback.
<asp:HiddenField id="Data1HiddenField" runat="server" />
<asp:HiddenField id="Data2HiddenField" runat="server" />
Your client script should include the ClientID values to handle server side naming container modifications. Using the <%= expression %> syntax (Expression Builder) requires that your script (or at least this part of the script) be maintain within your .aspx file. If you maintain your JavaScript in external files, you can "register" a simple function that gets called by your main JavaScript to move the data and compose that function server side along with the required ClientIDs. See ClientScriptManager.RegisterClientScriptBlock().
var data1 = "data value 1";
var data2 = "data value 2";
$("#<%= Data1HiddenField.ClientID %>").val(data1);
$("#<%= Data2HiddenField.ClientID %>").val(data2);
Your server side code then looks like this:
string data1 = Data1HiddenField.Value;
string data2 = Data2HiddenField.Value;
There are certainly other techniques to passing multiple data values but I have found this to be both simple and easy to maintain. You can pass all kinds of data and encode it using JSON if needed.
I have used multiple parameters before by building and splitting a string.
eg
string args = String.Format("{0};{1}", bolID, ControlID);
You can then pass this in to the arguments for the postback, and when checking for the postback arguments just split the string based on your speration character (in this case ';')