I am using an external JavaScript file which will give me a message when a Dropdown list value is not selected. It is set 'Select' by default. I have tried a lot of things I found while searching, but it is not running on my site. I am using Visual studio 2013 with 4.5 frame work.
Below is the code I have tried.
function unicollege()
{
var ddlObject = document.getElementById("<%=ddlType.ClientID%>");
var selectedValue = ddlObject.options[ddlObject.selectedIndex].value;
var e = document.getElementById("ddlLocation");
var selectedLocation = e.options[e.selectedIndex].value;
// .option and .value property are not available in my program.
}
Here is what needs to be in your page to use the external javascript file:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptInclude(
this,
typeof(Page),
"",
ResolveClientUrl("JavaScript1.js"));
}
In your aspx markup use a variable for your ddl to reference in your external javascript file:
<script type="text/javascript">
var ddl = "<%=ddlList.ClientID%>";
</script>
and in your external javascript file:
/// <reference path="WebForm1.aspx" />
function unicollege() {
var ddlObject = document.getElementById(ddl);
var selectedValue = ddlObject.options[ddlObject.selectedIndex].value;
}
you dont really need to think this much complex.
i do these kind of work every day a thousand times.
function unicollege()
{
var ddlSelectedValue = document.getElementById("ddlType").value;
}
this i just sent u after testing..it is going to work perfectly fine and i am doing it for a long time.however be careful about the postback problems if they happen.
Related
I am trying to call a c# function from JavaScript but the problem is, I need to pass a JS parameter for the function. How can I do this?
Here's my Js
var categoryLists = <%= this.javaSerial.Serialize(this.categoryList) %>;
function addInput(type, value, name, id, onclick, parentId) {
var element = document.createElement("input");
element.type = type;
element.value = value;
element.name = name;
element.id = id;
element.onclick = onclick;
element.src = "trash.png";
element.style.width = "25px";
element.style.height = "25px";
element.style.marginBottom = "3%";
var parent = document.getElementById(parentId);
parent.appendChild(element);
}
function addBreak(parentId) {
var br = document.createElement("br");
var parent = document.getElementById(parentId);
parent.appendChild(br);
}
window.onload = function () {
alert(this.categoryLists.length);
for (var j = 0; j < this.categoryLists.length; j++) {
var temp = "button" + j;
addInput('image', '', temp, temp, <%=DeleteCategory(%>+categoryLists[j]), 'rightdiv');
addBreak('rightdiv');
}
}
categoryLists[j] is my paramter
Here's the c# code
public void DeleteCategory(string category){
}
public JavaScriptSerializer javaSerial = new JavaScriptSerializer();
Update- I call c# functions this way... <%= function()%> and they work fine.
Thank you in advance
Update- with all the comments, I have tried using ajax or jquery - i am not sure what this is ... now my js looks like this and its broken... are there syntax issues?
$(function () {
function addInput(type, value, name, id, onclick, parentId) {
var element = document.createElement("input");
element.type = type;
element.value = value;
element.name = name;
element.id = id;
element.onclick = onclick;
element.src = "trash.png";
element.style.width = "25px";
element.style.height = "28px";
element.style.marginBottom = "3%";
var parent = document.getElementById(parentId);
parent.appendChild(element);
}
function addBreak(parentId) {
var br = document.createElement("br");
var parent = document.getElementById(parentId);
parent.appendChild(br);
}
for (var j = 0; j < this.categoryLists.length; j++) {
var temp = "button" + j;
addInput('image', '', temp, temp, temp, 'rightdiv');
addBreak('rightdiv');
}
});
You have quite a few ways to do this.
You can use the cheater approach. Drop in a text box, and a standard button (that will call server side code behind). (set clientID mode for this button and text box as static).
<asp:Button ID="btnHidden" runat="server" Text="hidden but" />
<asp:TextBox ID="TextHiddenBox" runat="server" ClientIDMode="Static" ></asp:TextBox>
Ok, now in your js you can go:
<script>
// set the value we want to pass in the hidden text box
$('#txtHidden').value("abc");
$('#hiddenButton').click;
<script>
Note: above is jQuery syntax.
You could do this: (pure js no jQuery)
var myvaluetopass = "this is some text to pass as variable";
document.getElementById('<%= TextHiddenBox.ClientID %>').value = myvaluetopass;
document.getElementById('<%= btnHidden.ClientID %>').click();
so you don't have to introduce jQuery here - it can be some "time" and "hassle" to setup + get jQuery working.
So, the above will simple click on the hidden button, and the hidden text box will have the value that the code behind can work with. Once you wire up the above?
Then hide the button and the text box like this:
<asp:Button ID="btnHidden" runat="server" Text="hidden but" style="display:none"/>
<asp:TextBox ID="TextHiddenBox" runat="server" ClientIDMode="Static" style="display:none" ></asp:TextBox>
Now, the above is certainly somewhat "klugey". But when you starting out, it can work quite well. So, you set the value of some text box (often hidden), and then with js you FIRE the click event of another button (again often hidden). This now gets you a easy way to run one particular code behind routine, and not have to wire up complex ajax code.
The next approach? Well, fire a post back command. This again like the above hidden button trick assumes you need/want a post back here in addition to calling that one routine. this approach is somewhat better in that you don't have to drop on the form two hidden controls.
You ALSO need to drop in the script manager for this to work (don't know why). But you can do this in your code:
var myvaluetopass = "this is some text to pass as variable";
__doPostBack("MyCoolEventName", myvaluetopass);
So, the above fires a page post back, and then in the load event, we have this:
If Request("__EVENTTARGET") = "MyCoolEventName" Then
Dim str As String = Request("__EVENTARGUMENT")
Debug.Print("passed value = " & str)
End If
or as C#
if (Request("__EVENTTARGET") == "MyCoolEventName")
{
string str = Request("__EVENTARGUMENT");
Debug.Print("passed value = " + str);
}
So the above are some simple ways.
The ALL above ideas do cause a full page post-back to run. Now, if the routine you calling DOES need to set/get/change/deal with/see any control on the page, then of course one does need and want that all important page post back.
Last but not least? Well, you can do a ajax call, and that will call a specific routine on your page, pass values (if you want), and ONLY run that one routine. This can be VERY nice, it fast, and you do NOT get a full page post back. So, if the routine you need to run does not have to modify, or do much of anything on the web page, then ajax is certainly the best way to go (assuming that the routine you calling does NOT need to modify or change things on the page - since as noted, no page post-back will occur. And if you looking to use that value with code behind and modify things on the page, then you will need a post-back.
But, lets assume you do need to pass one, or do values.
Well, I suggest jQuery - it just makes the code a bit easier to write.
So, say in your web page, you have this simple sub, and want to pass two values:
<WebMethod()>
Public Shared Sub MySimpleSub(MyCoolPassValue As String, Age As Integer)
Debug.Print("passed string value = " & MyCoolPassValue & vbCrLf & "Age = " & Age.ToString)
End Sub
or:
[WebMethod()]
public static void MySimpleSub(string MyCoolPassValue, int Age)
{
Debug.Print("passed string value = " + MyCoolPassValue + Constants.vbCrLf + "Age = " + Age.ToString());
}
So in above, it just a public sub. (in the code behind for that web page).
(note the Shared - it HAS to be Static sub - since we calling the page - but don't have the full class object model).
We also need a
Imports System.Web.Services
Ok, now to call the above as ajax?
We get this:
var myvaluetopass = "this is some text to pass as variable";
var age = 23;
$.ajax({
type: "POST",
async: true,
url: 'OnePicture.aspx/MySimpleSub',
data: JSON.stringify({MyCoolPassValue: myvaluetopass, Age: age}),
contentType: "application/json; charset=utf-8",
datatype: "json"
}
);
}
So in above, we passed two values to the sub in the web form.
The above did assume jQuery. I can write it out as pure JavaScript, but the above thus gives;
How to pass values - hidden control idea.
Or use __dopostback - this gets rid of the requirement to have a button + hidden text box
(and use style="display:none" to hide the button and text box above (if you using that idea, and get it working).
As noted, I don't know why, but you have to drop a Scriptmanager into the page if you going to use dopostback. (or pass a valid control ref as the first parameter - it will just to your button code behind routine). But, my dopostback example simple gets/grabs the value in teh page load event (event args).
And then last but not least, we pass a value direction to a web method (sub) in that page - this is a ajax call, and just keep VERY much in mind that the code for this routine has to work without assuming that a page post-back occurred (compared to all previous examples that assumed you need a post back).
I have tried below approach.
I used one hidden field on aspx page named hdnTime.
Then I assigned value to hidden field in javascript function.
<script type='text/javascript'>
function getLocalTimeZone() {
document.getElementById('ctl00_bcr_hdnTime').value = 10;
var hidden = document.getElementById('ctl00_bcr_hdnTime');
var timezone = String(new Date());
hidden.value = timezone.substring(timezone.lastIndexOf('(') + 1).replace(')', '').trim();
}
Then on C# page load I tried below code.
ScriptManager.RegisterStartupScript(Page, GetType(), "disp_confirm", "getLocalTimeZone()", true);
string test = hdnTime.Value;
But I am getting blank value for hdnTime.
Please let me know if I missing something here.
Page_Load event is executed before document.ready so anything set in document.ready won't be available in Page_Load event
You can set value on click of a button than in c# you can get that value.
I am loading the value of string myvalue (global string) in array arr in javascript by
function hello()
{
alert("hi");
var arr=[<% myvalue %>];
alert(arr);
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
myvalue="1234";
Page.ClientScript.RegisterStartupScript(GetType(), "whatiskey", "hello();", true);
}
and updating myvalue on listbox1.item select and calling method which updates value of arr, but javascript arr does not load the new value
you have to put double quotes and write it like:
var arr=["<%=myvalue %>"];
or more better way :
var arr= new Array();
arr.push("<%=myvalue %>");
Register ListBox1 as partial post back element could also be one of the reason.
are you able debug, that ListBox1_SelectedIndexChanged is being called.
You need to something like below to stop this from multiple time registered, this can one of the reason not to call hello(). Use F12 to investigate the rendered HTML.
// Check to see if the client script is already registered.
if (!Page.ClientScript.IsClientScriptBlockRegistered(cstype, csname2))
{
Page.ClientScript.RegisterStartupScript(GetType(), "aNewKey", "hello();", true);
}
I've look an found only a similar post and didn't really answer my question or maybe they did but I didn't understand. The post I read was this one: Why does this javascript variable I'm creating via C# only get updated once?
I'm using a paged gridview and every time it's object data source runs the SelectCountMethod, I use the returning value on javascript. But, I've noticed that even thought that same returned value changes, on the server side. On javascript this value doesn't update.
My program is quite long but I'll use a basic example and hopefully some of you will understand it.
Client side:
function SomeFuntion()
{
alert("<%=num%>");
}
Server side:
//Global variable
Public Static int num = 0;
Public int SelectCountMethod()
{
var num = SomeMethod(); //Returns int
return num;
}
For example, on the server side num returns 60 and then this value updates to 7. On the server side num equals 7 but on the client side it's still 60. Is there a way to update the client sides value?
I apologies for my poor typing skills, English is not my native language.
Some examples might be helpful and thanks in advance.
I noticed that it doesn't mater where I update this variable(on selectCount method or any other method), on the client side doesn't update.
Taking a look at your client-side code, the "<%=num%>" is actually run on the server. If you examined the source in your browser, what you'll see is:
function SomeFuntion()
{
alert("60");
}
As you can see--there is no variable to update. In order to see that "60" change to "7", you'd have to refresh the client to pick up the new value that the server has for "num".
You could modify your JS method like this
var myMsg = <%=num%>;
function SomeFuntion()
{
alert(myMsg);
}
and in the codebehind
public int num = 60;
public int SelectCountMethod()
{
num = SomeMethod(); //Returns int
ScriptManager.RegisterStartupScript(this,
this.GetType(),
"Funct",
"myMsg = " + num + ";",
true);
return num;
}
So every time your method SelectCountMethod() is called, your JS variable myMsg get a new value because of the line ScriptManager.RegisterStartupScript
Without your server side code, we won't be able to find the ideal solution. However, you could potentially do the following:
Use a Hidden Field to store the value.
Use a global variable for the page, to pass the value to global variable in your JavaScript.
The easiest would be the Hidden Field, the reason is you can easily modify the data on both Client and Server without any real issues. You'll want to ensure that you do not modify the state to often.
<input type="hidden" id="hdTimer" runat="server" />
Then you can do your JavaScript, such as:
$('#Example').on('change', function () {
$('#hdTimer').val('60');
});
Now throughout the Client code you'll be able to modify the field with no issues, but when you need to submit a form, for a PostBack. You can use the field server side:
var content = hdTimer.value;
As I noted though, excessive cross manipulation may cause an issue at some point. Depending on the complexity. Your other approach would be the Global.
// Server Side
var example = 60;
protected void Page_Load(object sender, EventArgs e)
{
}
So this Global will hold the value, but when you reinitialize the value at Page Load it will hold be able to push an updated value to your JavaScript:
//Client Side:
var example = '<%= example %>';
The key though, will be to ensure you properly reinitialize the value.
When you do a PostBack your page is reinitialized, which can modify values on you if you aren't aware. This is incredibly important.
Use an HttpHandler and jQuery. Google is your friend, there are several examples on SO as well.
I found a possible solution, inefficient, but it will have to do. I have a search textbox that every time the search button is clicked, updates the grid view with the retrieved data from a data base. When the Onclick is called it binds the data source with the gridView. What I did was call the SelectCountMethod again right below the binding and used the same parameters I had stored on the Object data source as paramaters for the selectCountMethod. Then the amount returned by the selectCount I stored it on a hiddenField and that's it.
//Global variables
string _param1 = string.Empty,
_param2 = string.Empty;
//On click method for search btn
protected void OnSearch(object sender, EventArgs e)
{
gv.DataBind();
someHiddenField = SelectCountMethod(param1, param2);
}
protected void OnSelecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
try
{
e.InputParameters["Param1"] = param1;
_param1 = param1
e.InputParameters["Param2"] = param2;
_param2 = param2;
}
catch (Exception ex)
{
cvServerError.IsValid = false;
cvServerError.ErrorMessage = ex.Message;
}
}
I have a client side function by JavaScipt for FocusedRowChanged in my ASPxGridView.
In this function I post gvMore.GetFocusedRowIndex() to my CallBackPanel PerformCallback.
I save FocusedRowIndex in to ri variable ( var ri = gvMore.GetFocusedRowIndex(); )
and then I remove focus for row ( gvMore.SetFocusedRowIndex(-1); )
Now how can I Change GridView row[ri] color after SetFocusedRowIndex(-1); ?
function OnGridFocusedRowChanged() {
if (gvMore.GetFocusedRowIndex() > -1)
CallBackPanel_FindPlcyCar.PerformCallback(gvMore.GetFocusedRowIndex());
var ri = gvMore.GetFocusedRowIndex();
gvMore.SetFocusedRowIndex(-1);
// *???*
}
what JavaScript code is necessary for ??? Line?
Please answer here and do not redirect me to another link please.
Thanks a lot
You can use the
OnHtmlRowPrepared="gvMore_HtmlRowPrepared"
on the aspx file at the ASPxGridview tag and implement it as follows on the cs file:
public protected gvMore_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
{
e.Row.Attributes.Add("id",e.Row.RowIndex.ToString());
}
On the client side you can then change the // ??? part with
document.getElementById(ri).style.Background = "#122334"
or whatever other color you might want.
I have not executed the code, and there might be more ins and outs but that's the gist of it.
Finally I used allowrowselect instead of allowrowfocus.
And RowClick client side Event.
And e.visibleIndex in RowClick client side Event.
allowrowselect changes the backcolor itself.