I have a parameter for a method, that should be a string and I can't come up with how to <% *.ClientID %> to the thing as a variable like that. Since its a variable i can't wrap it in quotes since it will be taken literally and when I use the parameter like a variable (as you're supposed to) i get an ASP error saying it doesn't exist in the context (reading it literally).
Any Clues?
thanks guys
Code Sample
function next(currentControl, maxLength, nextControl) {
if (document.getElementById( currentControl<%=.ClientID %>).value.length >= maxLength) {
document.getElementById( nextControl<%=.ClientID %>).focus();
}
return false;
}
Call Sample
wValCode.Attributes.Add("onkeyup","next('wValCode','3','wValThree')");
I know probably a primitive way of adding the attribute, but its how it was explained to me. I picked up ASP on the fly so don't be too hard on me ;)
Static HTML
<input name="ctl00$ContentPlaceHolder2$wValThree" type="text" id="ctl00_ContentPlaceHolder2_wValThree" style="width:33px;">
That is the only related reference I can find in the static html. Would it have been added in one of ASPs convoluted js files?
Given you're binding the key events from code behind, you can just reference the client IDs at the time that you're doing the binding:
wValCode.Attributes.Add("onkeyup","next('" + wValCode.ClientID + "', '3', '" + wValThree.ClientID + "')");
Then, you already have the client IDs passed as parameters to the javascript function
function next(currentControl, maxLength, nextControl) {
if (document.getElementById(currentControl).value.length >= maxLength) {
document.getElementById(nextControl).focus();
}
return false;
}
An even better option is to pass a reference to the calling object as the first parameter, using the this keyword:
//code behind
wValCode.Attributes.Add("onkeyup","next(this, '3', '" + wValThree.ClientID + "')");
//javascript function
function next(currentControl, maxLength, nextControl) {
if (currentControl.value.length >= maxLength) {
document.getElementById(nextControl).focus();
}
return false;
}
Try moving the dot outside the ASP.NET tag:
currentControl.<%= ClientID %>
Related
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!
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);
So I'm fairly new to the .NET framework, but what I'm trying to do is execute the following jQuery code:
$(document).on('click', 'a[data-link]', function () {
var $this = $(this);
url = $this.data('link');
$("#imagePreview").load("imageProcess.aspx?"+url);
where url holds something like "model=2k01&type=black&category=variable".
Unfortunately this doesn't work, becuase when I do something as simple as a Response.Write() in the aspx file, the div tag imagePreview doesn't do anything. However, removing the ? + url part works, but then I can't send any data over to the aspx file. I'm doing it this way because every link a[data-link] has different data that's being sent over, and I need to find a dynamic way to achieve this. Any suggestions would be much appreciated.
UPDATE:
Here is the part in my html code that is generating the url stuff:
<a class='modelsBlue' href = '#' data-link='model=" + $(this).find('model').text() + "&type=" + category + "'>" + $(this).find("model").text() + "</a>
and #image preview is in my code as:
<div id = "imagePreview"></div>
When I try to run the code above, i get the following error which seems to be coming from the jQuery.js file:
Microsoft JScript runtime error: Syntax error, unrecognized expression: &type=AutoEarly
Here is the imageProcess.aspx.cs file, which right now is just outputting all images in the directory:
namespace ModelMonitoring
{
public partial class imageProcess : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("test");
foreach (var f in Directory.GetFiles(Directory.GetCurrentDirectory()))
{
Response.Write(f);
Response.Write("<br />");
}
}
}
}
SECOND UPDATE:
I don't get the error running in chrome or firefox, but the files are not being output.
Turns out it was a whitespace issue. I had to add a wrapper around:
$(this).find('model').text()
to read:
$.trim($(this).find('model').text())
becuase the xml file I was reading from had whitespace around the model name. Thanks to anyone who replied!
I am just learning how to use classes in my projects. I have been working on a DataAccessClass.cs and am doing well (I think).
Taking a break from data access, I decided to try to make a void into a class. This void sends a message to the client as a javascript alert. It works well, but has to be included on each page. When I tried to make it a class, I was informed that my class does not contain a definition for ClientScript. I included all the "using" directives from the original page to no avail... Any hints or suggestions would be greatly appreciated.
The original code:
//------------------------------------------------------------------------------
//Name: SendErrorMessageToClient
//Abstract: show alert on client side
//------------------------------------------------------------------------------
protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage)
{
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";
this.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
Messages are sent into this void like this:
if (DataAccessClass.OpenSqlConnection(ref Conn, strConn, out strErrorMessage) == false)
{
string strErrorType = "Database Connection Error:";
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
Or this:
catch (Exception excError)
{
string strErrorType = "Unhandled Exception:";
string strErrorMessage = excError.Message;
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
You are receiving the error as 'Clientscript' is a property derived from a System.Web.UI.Page and by moving into a separate class file, you no longer have access to this property.
You could solve this by passing in the page as well, and amending the code to
protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage, Page page)
{
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";
page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
ClientScript Property is part of the Page class that every ASPX page inherit from. Therefore you can not just use it from inside your class unless it (i.e. your class) has Page as its base class.
this. is for fields in your method in classes.
Why do you want to make this a class? It shouldn't be a class, it doesn't have any properties or fields, unless you can think of one. You do understand if you make it a class you would still have to intialize it on every page.
You could make it a static string method you would still have to include this on every page.
this.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
You'll need to pass the page into the function
SendErrorMessageToClient(Page page, string strErrorType, string strErrorMessage)
so that you can change
this.ClientScript...
to
page.ClientScript...
The reason being that ClientScript is part of the Page class
Or, possibly better, pass the ClientScript object, rather than page.
So your definition would look like
SendErrorMessageToClient(ClientScript clientScript, string strErrorType, string strErrorMessage) {
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = String.Format("<script type='text/javascript' language='javascript'>alert('{0}\\n\\n{1}');</script>",
strErrorType, strErrorMessage);
clientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
I'm having a bit of an issue with a mix between YUI's AJAX and a YUI Datatable. The AJAX request fires properly and I get back the correct data formatted as:
{NoteId:'" + result.NoteId + "', CreatedOn:'" + result.CreatedOn.ToShortDateString() +
"', UpdatedOn:'" + result.UpdatedOn.ToShortDateString() + "', CreatedBy:'" + result.CreatedBy +
"', NoteContent:'" + result.NoteContent + "'}
These match the table identities properly, and I ripped this formatting from the statement that initially creates the datatable (which works properly). I don't know if I have the 'onSuccess' messed up for my AJAX call or what, and this is my first time touching YUI.
Also, if I manually execute the noteTable.addRow and hard code the data, it works.
Code for the AJAX call and Table Update:
function addNote() {
var noteText = editor.get('element').value;
var id = '<%= Model.Menu.Level1Tab %>'
var lpqId = <%= Model.LpqID %>
var sUrl = "/Lpm/Notes";
var callback = {
success: function(o) {
noteTable.addRow(o.responseText);
},
failure: function(o) {
}
}
var transaction = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, 'id=' + id + '¬eContent=' + noteText + '¬eId=' + noteId + '&lpqId=' + lpqId);
}
I'm pretty well stuck on this, so if anyone could have a look and let me know where I messed something up, I'd appreciate it. If you need more info, I have plenty, including firebug debugging info.
Thanks in advance for the help
Looks like you need to convert the o.responseText from string to object. The JSON Utility can help you do that: http://developer.yahoo.com/yui/json/.
Incidentally, DataTable's DataSource integration can help manage these issues for you. This example (http://developer.yahoo.com/yui/examples/datatable/dt_xhrjson.html) shows you how to set up a DataSource and integrate it with a DataTable. Note how you can send a request to get some data from your server and then use one of the "onDataReturn..." methods (see "Loading data at runtime" under http://developer.yahoo.com/yui/datatable/#data) in your callback.