How to get a post back parameter value in code-behind - c#

I am triggering a postback event in aspx page as below:
__doPostBack('AddNewEmployeeType', "empl", "sick");
Code behind:
string val = Request.Params.Get("__EVENTTARGET");
By the above code i was able to get only one first value, but my intention is to get all three parameter values. How can I achieve this?

Use the __EVENTARGUMENT:
string parameter = Request["__EVENTARGUMENT"];
string val = Request.Params.Get("__EVENTTARGET"); // AddNewEmployeeType
Here's a tutorial: Understanding the JavaScript __doPostBack Function
If you need to pass multiple parameters back to codebehind you need to split it by a delimiter yourself. You could for example use the pipe |:
__doPostBack('AddNewEmployeeType', "empl|sick");
and in codebehind:
string parameter = Request["__EVENTARGUMENT"];
string[] allParams = parameter.Split('|');

Your call to __doPostBack is technically incorrect. If you check the source of an ASP.NET page, you'll see the function:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
Note it has only 2 parameters. If you need to pass more values, you need to stuff them into the eventArgument parameter.
How you do this is up to you - use a comma-separated list, or JSON, or whatever suits you, and parse this value (by accessing Request["__EVENTARGUMENT"]) on the server.

Alternatives
Postbacks are not supposed to be handled like that. If a control is raising postbacks, and if it's an User Control, it should implement IPostBackDataHandler. and you should assign an EventHandler to it, even if it's a custom one.
References
https://msdn.microsoft.com/pt-br/library/system.web.ui.ipostbackdatahandler(v=vs.110).aspx

Related

how to make cookie in asp.net that takes url query string

intern in company working with asp.net and sitecore here
My very first assignment has to do with adding support for a query parameter that can will enable the editor to see some key names of some buttons for a page.
Now i was thinking that i would make a cookie with httpcookie in the correct controller and somehow get the query parameter into the cookie, could that be done in a way?
many thanks?
You can use a URL querystring parameter to get the value you need on Page Load and then set controls accordingly. As for storing Values you can store whatever you need in ViewState or SessionState and look them up when you need to.
Example below:
private void Page_Load()
{
if(Request.QueryString["switch"] !== null)
{
if(Request.QueryString["switch"].ToString()) == "on")
{
button.Visible = true;
ViewState["someval"] = hiddenVal.Text;
}
else
{
button.Visible = false;
}
}
}

Replace Query String of a page

I want to replace the Query String of my page like this-
firstly I move to this page on clicking on menu bar Items by setting this URL-
Response.Redirect("SearchtWorkForceReport.aspx?page=Search");
then I want to change url like this-
"SearchtWorkForceReport.aspx?page=Search" to "SearchtWorkForceReport.aspx?page=Edit" on a check box change event.
I try this code-
string strQueryString = Request.QueryString.ToString();
if (strQueryString.Contains("page"))
{
strQueryString = strQueryString.Replace("Search", "Edit");
}
and it'll replace the Query String but on page load if I get the query string should give again the previous set string.
type = Request.QueryString["page"].ToString();
You can't edit query string of the page by editing Request.QueryString. you should redirect to current page. use code below:
if (Request.RawUrl.Contains("page"))
{
Response.Redirect(Request.RawUrl.Replace("Search", "Edit"))
}
Query strings are provided by your clients, changing your copy server-side does not have any effect.
You have to redirect your client to the new URL with the new query string:
Response.Redirect("SearchtWorkForceReport.aspx?page=Edit");
From your question my understanding is you are trying to change the query string in check box change event on the second page.
so write this code in checkbox change event
Response.Redirect("SearchtWorkForceReport.aspx?page=Edit");
and in page load check the querystring
string type = Request.QueryString["page"].ToString();
if(type=="Edit")
{
//what you want to do?
}

Invoke JavaScript from C# code behind [duplicate]

This question already has answers here:
Calling JavaScript Function From CodeBehind
(21 answers)
Closed 9 years ago.
I am trying to learn asp.net. Assuming that I have this code:
if (command.ExecuteNonQuery() == 0)
{
// JavaScript like alert("true");
}
else
{
// JavaScript like alert("false");
}
How to I can invoke JavaScript from C# code behind? How to do that by putting that JavaScript in Scripts directory which is created by default in MS Visual Studio?
Here is method I will use from time to time to send a pop message from the code behind. I try to avoid having to do this - but sometimes I need to.
private void LoadClientScriptMessage(string message)
{
StringBuilder script = new StringBuilder();
script.Append(#"<script language='javascript'>");
script.Append(#"alert('" + message + "');");
script.Append(#"</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "messageScript", script.ToString());
}
You can use RegisterStartupScript to load a javascript function from CodeBehind.
Please note that javascript will only run at client side when the page is render at client's browser.
Regular Page
Page.ClientScript.RegisterStartupScript(this.GetType(), "myfunc" + UniqueID,
"myJavascriptFunction();", true);
Ajax Page
You need to use ScriptManager if you use ajax.
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myfunc" + UniqueID,
"myJavascriptFunction();", true);
Usually these "startupscripts" are handy for translations or passing settings to javascript.
Although the solution Mike provided is correct on the .Net side I doubt in a clean (read: no spaghetti code) production environment this is a good practice. It would be better to add .Net variables to a javascript object like so:
// GA example
public static string GetAnalyticsSettingsScript()
{
var settings = new StringBuilder();
var logged = ProjectContext.CurrentUser != null ? "Logged" : "Not Logged";
var account = Configuration.Configuration.GoogleAnalyticsAccount;
// check the required objects since it might not yet exist
settings.AppendLine("Project = window.Project || {};");
settings.AppendLine("Project.analytics = Project.analytics || {};");
settings.AppendLine("Project.analytics.settings = Project.analytics.settings || {};");
settings.AppendFormat("Project.analytics.settings.account = '{0}';", account);
settings.AppendLine();
settings.AppendFormat("Project.analytics.settings.logged = '{0}';", logged);
settings.AppendLine();
return settings.ToString();
}
And then use the common Page.ClientScript.RegisterStartupScript to add it to the HTML.
private void RegisterAnalyticsSettingsScript()
{
string script = GoogleAnalyticsConfiguration.GetAnalyticsSettingsScript();
if (!string.IsNullOrEmpty(script))
{
Page.ClientScript.RegisterStartupScript(GetType(), "AnalyticsSettings", script, true);
}
}
On the JavaScript side it might look like this:
// IIFE
(function($){
// 1. CONFIGURATION
var cfg = {
trackingSetup: {
account: "UA-xxx-1",
allowLinker: true,
domainName: "auto",
siteSpeedSampleRate: 100,
pluginUrl: "//www.google-analytics.com/plugins/ga/inpage_linkid.js"
},
customVariablesSetup: {
usertype: {
slot: 1,
property: "User_type",
value: "Not Logged",
scope: 1
}
}
};
// 2. DOM PROJECT OBJECT
window.Project = window.Project || {};
window.Project.analytics = {
init: function(){
// loading ga.js here with ajax
},
activate: function(){
var proj = this,
account = proj.settings.account || cfg.trackingSetup.account,
logged = proj.settings.logged || cfg.customVariablesSetup.usertype.value;
// override the cfg with settings from .net
cfg.trackingSetup.account = account;
cfg.customVariablesSetup.usertype.value = logged;
// binding events, and more ...
}
};
// 3. INITIALIZE ON LOAD
Project.analytics.init();
// 4. ACTIVATE ONCE THE DOM IS READY
$(function () {
Project.analytics.activate();
});
}(jQuery));
The advantage with this setup is you can load an asynchronous object and override the settings of this object by .Net. Using a configuration object you directly inject javascript into the object and override it when found.
This approach allows me to easily get translation strings, settings, and so on ...
It requires a little bit knowledge of both.
Please note the real power of tis approach lies in the "direct initialization" and "delayed activation". This is necessary as you might not know when (during loading of the page) these object are live. The delay helps overriding the proper objects.
This might be a long shot, but sometimes I need a c# property/value from the server side displaying or manipulated on the client side.
c# code behind page
public string Name {get; set;}
JavaScript on Aspx page
var name = '<%=Name%>';
Populating to client side is generally easier, depending on your issue. Just a thought!

how to passing value codebehind C# to javascript

Any one can help me..I want to pass the C# value to javascript..I only get pass 2 values only to the javascript..I dont know how to pass a tbSTime,tbETime and tbIndo2..Please help me..Thank You
This is code behind:
{
// get the meeting info based on the id
int id = Convert.ToInt32(Request["id"]);
MeetingClass.MeetingInfo m = MeetingClass.MeetingInfo.GetInfo(id);
// fill data
tbtitle2.Value = m.Title;
tbdate2.Value = m.Date.ToShortDateString();
tbSTime.Value = m.StartTime.ToShortTimeString();
tbETime.Value = m.EndTime.ToShortTimeString();
tbIndo2.Value = m.Desc;
}
And this is javascript:
function getInfo() {
$('#<%=tbtitle.ClientID%>').val($('#<%=tbtitle2.ClientID%>').val());
$('#<%=tbdate.ClientID%>').val($('#<%=tbdate2.ClientID%>').val());
}
From what I can tell on your code, you are setting an asp:HiddenField (since you are using .Value) and then using that to populate your asp:TextBox w/ jQuery. If that is the case, then you need to do something like this.
$('#<%=aspTextBoxName1.ClientID%>').val($('#<%=tbSTime.ClientID%>').val());
$('#<%=aspTextBoxName2.ClientID%>').val($('#<%=tbETime.ClientID%>').val());
$('#<%=aspTextBoxName3.ClientID%>').val($('#<%=tbIndo2.ClientID%>').val());
Where aspTextBoxName1, aspTextBoxName2, aspTextBoxName3 are the names of your new textboxes.
I don't know if you really need those hidden form fields, there are easier ways to do this if you don't.
in controller:
ViewBag.tbSTime = tbSTime;
in view:
$('#<%=tbtitle.ClientID%>').val("<%= ViewBag.tbSTime %>");
Iam sorry but iam not sure what exactly you need, but from what i understood i can provide you with this:
If You want to send some value from Server side variables to Javascript function one way you can do this as follows,
function abc(x,y)
{
//Do you things here
}
and from server side call javascript code as follows
string a=textbox1.text;
string b=textbox2.text;
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "abc("+a+","+b+");", true);

How to read session values using jQuery

I am using c# and jQuery.
I have below code where I am setting the Session Variable using C# code.
if (!string.IsNullOrEmpty(results))
{
string[] array = results.Split(',');
string firstName = array[0];
string lastName = array[1];
string activeCardNo = array[2];
string memberShipTier = array[3];
string accessToken = array[4];
Session["skyFirstName"] = firstName.ToString();
Session["skyLastName"] = lastName.ToString();
Session["skyActiveCardNo"] = activeCardNo.ToString();
Session["skyMemberShipTier"] = memberShipTier.ToString();
Session["boolSignOn"] = "true";
Response.Redirect(fromPage);
Response.End();
}
Now I want to read these values (Session["skyFirstName"]) using jQuery so that I can set in my elements. Please suggest.
Session values are stored on the server and it is impossible to read them with client side javascript. One way to achieve this would be to expose some server side script or generic handler which would return the corresponding session value given a key and then use jQuery to send an AJAX request to this handler and read the value. You should be aware that by doing this the user can read all his session values. Be warned that exposing the same script for writing session values could be catastrophic from security standpoint.
Here's an example:
public class ReadSession : IHttpHandler, IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Write(new JavaScriptSerializer().Serialize(new
{
Key = context.Request["key"],
Value = context.Session[context.Request["key"]]
}));
}
public bool IsReusable
{
get { return true; }
}
}
and then query it:
$.getJSON('/ReadSession.ashx', { key: 'skyFirstName' }, function(result) {
alert(result.Value);
});
jquery runs on the client, which cannot directly access your server-side-session values. one solution is to provide a webservice which returns these values and use the webservice, another one would be to include the values in the page-response as JSON (e.g.) and access them on the client.
You cannot access the session variables with javascript as the session variables are server side rather than client side.
One work around that has already been mentioned is to use ajax to allow the javascript to communicate with the server side. This is fine, but possibly overly complicated for what you need.
Another, simpler solution would be to output the session variables into hidden input fields or as javascript variables in script tags which you can then access with the javascript.
jQuery is javascript, so in order to have those variables available you need to print out html code (at least one script tag) where you set the read-out session variables from C# as javascript variable.
An alternative would be to use an ajax request to get the session variables from a server script.

Categories