how to passing value codebehind C# to javascript - c#

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);

Related

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

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

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!

What is the recommended way to call a javascript function from C# using the WinForms GeckoFX control?

The questions says it all. I have everything wired up and know how to send messages from the browser html to c#, but not the other way.
I should be able to do something like:
browserControl.JSCall("myFunction('Dave','Smith');");
...and in the web code:
function myFunction(firstName, lastName) {
$("#mydiv").text(firstName + ' ' + lastName);
}
Thanks - Dave
You can do this using Navigate:
browserControl.Navigate("javascript:void(myFunction('Dave','Smith'))");
Note, I find that the code isn't actually run until the application event loop executes. If that's a problem for you, you might be able to follow the Navigate call with
Application.DoEvents();
Make sure you consider the dangers of calling DoEvents explicitly.
I know about AutoJSContext class so there is no need for passing javascript to Navigate().
string outString = "";
using (Gecko.AutoJSContext java = new Gecko.AutoJSContext(geckoWebBrowser1.JSContext))
{
java.EvaluateScript(#"window.alert('alert')", out outString );
}
Dear #SturmCoder and #DavidCornelson are right.
but it seems that for version 60.0.24.0
geckoWebBrowser1.JSCall()
and
Gecko.AutoJSContext() which accepts geckoWebBrowser1.JSContext
are absolete and instead of geckoWebBrowser1.JSContext you should write geckoWebBrowser1.Window
and for me this codes works :
string result = "";
using (Gecko.AutoJSContext js= new Gecko.AutoJSContext(geckoWebBrowser1.Window))
{
js.EvaluateScript("myFunction('Dave','Smith');", out result);
}
or even if the website has jQuery you can run like this :
string result = "";
using (Gecko.AutoJSContext js= new Gecko.AutoJSContext(geckoWebBrowser1.Window))
{
js.EvaluateScript(#"alert($('#txt_username').val())", out result);
}
Besides using Navigate method, you have this another workaround:
var script = geckofx.Document.CreateElement("script");
script.TextContent = js;
geckofx.Document.GetElementsByTagName("head").First().AppendChild(script);

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.

Implementing javascript in c# code behind

Morning all.
I have the following javascript in my code in front
<script type="text/javascript" src="~/VDSReporting/jquery.js"></script> <script type="text/javascript">
function ShowImage() {
document.getElementById('tbxProdAC')
.style.backgroundImage = 'url(/images/vds/progress.gif)';
document.getElementById('tbxProdAC')
.style.backgroundRepeat = 'no-repeat';
document.getElementById('tbxProdAC')
.style.backgroundPosition = 'right';
}
function HideImage() {
document.getElementById('tbxProdAC')
.style.backgroundImage = 'none';
}
</script>
How do I go about 'converting' this and only having it present in c# code behind?
Please excuse my ignorance, I'm completely out of my depth here!
If this is a progress image you are showing (seems so from the image name), then why would you want to do that server side? That will kind of defeat the whole purpose of a progress image. This seem like it belong on the client side, so keep it there.
Update
You don't need to use the code behind to render the script just to get the client id's. You can do something like this:
function ShowImage() {
document.getElementById('<%=tbxProdAC.ClientID%>')
.style.backgroundImage = 'url(/images/vds/progress.gif)';
document.getElementById('<%=tbxProdAC.ClientID%>')
.style.backgroundRepeat = 'no-repeat';
document.getElementById('<%=tbxProdAC.ClientID%>')
.style.backgroundPosition = 'right';
}
function HideImage() {
document.getElementById('<%=tbxProdAC.ClientID%>')
.style.backgroundImage = 'none';
}
Here I use <%=tbxProdAC.ClientID%> to get the id of the control. This is a lot more readable then using the code behind to render the script.
I need some javascript to be run from the server side and this worked for me -
if (!this.ClientScript.IsStartupScriptRegistered("StartDown"))
{
string scriptString = #"alert(""some javascript"");location.href='MyPage.aspx';";
this.ClientScript.RegisterStartupScript(Page.GetType(), "StartDown", scriptString, true);
}
Hope this helps..

Categories