I want call jQuery Function from code behind because I must send variable for function.
I Used this code in code behind :
ClientScript.RegisterClientScriptBlock(this.GetType(), "myfunction", "ValidateTB("+ num+ "," + count +");", true);
And my function is :
function ValidateTB(num,count) {
var check = false;
alert("alert");
for (var i = 0; i < num; i = i + 1) {
check = false;
for (var j = 0; j < count; j = j + 1) {
var id = "myTextBox" + i + j;
if ($("input[type='text']").val().length > 0) {
check = true;
}
if (check == false) {
$("#error").text("error");
return false;
}
}
}
return true;
};
Why my function doesn’t work? It sounds my function doesn’t run
Make sure that this function is declared in a <script> block which is in the <head> section.
Your code should look like this.
ClientScript.RegisterClientScriptBlock(this.GetType(), "myfunction", "return ValidateTB("+ num+ "," + count +");", true);
Your jquery function return true or false value, so you have to write "return" when you will call your function.
While calling any jquery code from codebehind make sure, you surround your code with $(document).ready. You need to change your codebehind call to below:
ClientScript.RegisterClientScriptBlock(this.GetType(), "myfunction", "$(document).ready(function(){ValidateTB('"+ num+ "','" + count +"');});", true);
Use RegisterStartupScript instead
Documentation
Suppose we have the following jquery class "ChangeDate" with some properties and an OnSelect event which will be invoked during selection,then if we want to use this class in codebehind and change it,then one way is to take a stringbuilder and do as follows,
$(document).ready(function () {
$('.ChangeDate').datepicker({
beforeShowDay: $.datepicker.noWeekends,
changeMonth: true,
changeYear: true,
dateFormat: 'mm/dd/yy',
yearRange: '-100:+100',
showButtonPanel: true,
onSelect: function (date) {
sMsg = sMsg + getErrorMessage('HME0002');
if (confirm(sMsg) == true) {
$('.ChangeDate').val('As of ' + date);
$(this).datepicker("hide");
return true;
}
else {
$('.ChangeDate').val('As of ' + oldD);
return false;
}
}
}); });
Taking StringBuilder in codebehind and append to it the function which is required and calling it using RegisterClientScriptBlock as follows
StringBuilder sb = new StringBuilder();
sb.Append("$(document).ready(function () {");
sb.Append("$('.ChangeDate').val('As of " + DateTime.Now.ToString("MM/dd/yyyy") + "');");
sb.Append("});");
BuildJSString("KEY", sb.ToString());
private void BuildJSString(string keyStr, string scriptStr)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), keyStr, scriptStr,true);
}
Related
I have a view which loads a partial on the change event of several dropdowns:
I have some javascript that calls an action:
$("#filterdd").on('change', function () {
var datefrom = $('#fromdt').val().replace("/", "-").replace("/", "-");
var dateto = $('#todt').val().replace("/", "-").replace("/", "-");
$("#partialexpcal").load('/home/experienceCalendarFilter?fromdt=' + datefrom + '&todt=' + dateto);
});
Then this returns a partial:
public ActionResult experienceCalendarFilter(string fromdt = "", string todt = "")
{
myModel model = new myModel();
model = gd.getstuff(fromdt, todt);
if (Request.IsAjaxRequest())
{
return PartialView("_expcalendar", model);
}
else
{
return View(model);
}
}
<div id="partialexpcal">
#Html.Partial("_expcalendar", Model)
</div>
I am using jQuery Datetimepicker which need to fire after the partial has loaded:
function afterload() {
$(".datefield").datepicker({ dateFormat: "dd/mm/yy", changeYear: true });
$(function () {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var ok = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
ok = false;
}
return ok;
});
$(".datefield").datepicker({ dateFormat: 'dd/mm/yy', changeYear: true });
});
}
I have tried all of the following in both the parent view and the partial where 'expcalfilterdiv' is the main container in the partial view:
$('#expcalfilterdiv').ready(function () {
alert("hit1");
afterload()
});
This hits but only on initial load not after the partial has been changed.
$('#expcalfilterdiv').live(function () {
alert("hit1");
afterload()
});
This doesn't hit at all.
$('#expcalfilterdiv').livequery(function () {
alert("hit1");
afterload()
});
Is there a way I can catch the Ajax success when doing it how I am?
If you see $.load() docs, you'll find that this function receives 3 parameters. The third one is complete, and this is a callback which will run once the load request has fulfilled. I.e. modify your load code adding a third parameter which can be a function definition, or the name of an existing function, that will be executed when load finishes:
$("#partialexpcal")
.load('/home/experienceCalendarFilter?fromdt=' + datefrom + '&todt=' + dateto,
function() { /* */});
or
$("#partialexpcal")
.load('/home/experienceCalendarFilter?fromdt=' + datefrom + '&todt=' + dateto,
functionToInvoke);
NOTE: in the docs the second parameter is dentoed as optional sith square brackets, so you can omit it and specify the third one directly
Load has a second parameter that is called once the AJAX call is completed, like below.
$("#partialexpcal").load('/home/experienceCalendarFilter?fromdt=' + datefrom + '&todt=' + dateto,function( response, status, xhr ){
//.. check for error here ...
afterload();
});
I have a function onRowClick called RowClick and is working fine. I am trying to move it to a button and call the function from the code behind. For some reason is not triggering the function.. Anyone knows why and how I can fix this?
aspx.cs
if (e.CommandName == "Addvoucher")
{
GridDataItem item = (GridDataItem)e.Item;
var id = item.GetDataKeyValue("RowID");
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "RowClick("+id+");", true);
}
aspx
<script>
var popUpObj;
function RowClick(sender, eventArgs) {
var filterId = eventArgs.getDataKeyValue('RowID');
popUpObj = window.open("voucher.aspx?param=" + filterId + "",
"ModalPopUp",
"toolbar=no," +
"scrollbars=no," +
"location=no," +
"statusbar=no," +
"menubar=no," +
"resizable=0," +
"width=530," +
"height=500," +
"left = 450," +
"top=130"
);
popUpObj.focus();
LoadModalDiv();
}
function LoadModalDiv()
{
var bcgDiv = document.getElementById("divBackground");
bcgDiv.style.display="block";
}
function HideModalDiv() {
var bcgDiv = document.getElementById("divBackground");
bcgDiv.style.display = "none";
}
</script>
IN page voucher.aspx
<script type = "text/javascript">
function OnClose() {
if (window.opener != null && !window.opener.closed) {
window.opener.location.reload(); //refreshing parent when popup close
// window.opener.HideModalDiv();
}
//if (window.closed==true) window.open("~/routedoc.aspx");
}
window.onunload = OnClose;
</script>
Change your js function like this
function RowClick(filterId) {
popUpObj = window.open("voucher.aspx?param=" + filterId + "",
"ModalPopUp",
"toolbar=no," +
"scrollbars=no," +
"location=no," +
"statusbar=no," +
"menubar=no," +
"resizable=0," +
"width=530," +
"height=500," +
"left = 450," +
"top=130"
);
popUpObj.focus();
LoadModalDiv();
}
There is no need of this line now var filterId = eventArgs.getDataKeyValue('RowID'); Now you can directly use the parameter filterId in your js function.
Calling JavaScript function on code behind i.e. On Page_Load
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
If you have UpdatePanel there then try like this
ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
Because you are calling RowClick() and in your code you are calling the second parameter eventArgs and actually it's an undefined value.
Make sure you pass the correct parameters.
Since you just calling a javscript function then I would recommend to just on the grid row data bound just assign the value to an anchor a tag or a button to just call the javascript.
The problem is you are not passing any arguments for that js function from server side but you are getting data key value in client function as in your edited question pass row id from server side and change the client side function as below,
function RowClick(rowId)
{
// use rowId
popUpObj = window.open("voucher.aspx?param=" + rowId + "",
}
I am making Gridview's Textbox visible true or false when user changes Dropdownlists selectedIndexchange event for that i have done following code
My .CS File code is as below:
protected void gvTaskList_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField hdn = (HiddenField)e.Row.FindControl("hdnStatus");
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlStatus");
TextBox txt = (TextBox)e.Row.FindControl("txtVal");
if (ddl != null)
{
ddl.Items.Add("Not Started");
ddl.Items.Add("In Progress");
ddl.Items.Add("Complete");
if (hdn != null)
{
ddl.SelectedValue = hdn.Value;
}
//ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
ddl.Attributes.Add("onChange", "return myFun(" + "'" + txt.ClientID + "'" +");");
}
}
}
catch (Exception ex)
{
Utility.ErrorList("EmpTaskList--RowdataBound", ex.ToString());
}
}
Note: My combobox and textbox both are in EditTmplate
Javascript code is as below
<script type="text/javascript">
function myFun(txtControl) {
var v = document.getElementById("<%=" + txtControl + "%>");
alert(v);
}
When i m changing dropdownlist index function is called and alert is showing null.
So can anyone please suggest me what i m doing wrong??
I don't think you want the server-side tags in your getElementById call:
var v = document.getElementById(txtControl);
int i = Convert.ToInt32(Session["sayfaTuru"]);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2(" + i + ")", true);
function f2(i) {
if (i == 1) {//CariKartHareketleri
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.location.href = window.opener.location.href; //çağıran sayfayı yeniliyor
}
else if (i == 2) {//islemler
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.__doPostBack('GridRefreshPanel.ClientID', '');
}
else if (i == 3) {//hizmet listesi
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.__doPostBack('GridRefreshPanel.ClientID', '');
}
}
it says i is undefined when I debug the code in f2(i).What am i doing wrong?
EDIT: I learned many things from this problem, but I still do not have an answer.I tried every idea given in the answers but i is still undefined...
EDIT: I still have no solution for undefined reasons :), but the answer I accepted would normally be my solution.
Have you tried debugging the server-side code to see if
int i = Convert.ToInt32(Session["sayfaTuru"]);
is giving you what you want in the first place?
Well seeing as how the above has been checked, I went ahead and created my own test, and it worked just fine. Here's the test I used:
JS:
<script type="text/javascript">
function f2(i, hiddenFieldId, updatePanelId) {
console.log(i + ', "' + hiddenFieldId + '", "' + updatePanelId + '"');
var hiddenField = window.opener.document.getElementById(hiddenFieldId);
switch (i) {
case 1: //CariKartHareketleri
hiddenField.value = "hello world 1";
window.opener.location.href = window.opener.location.href; //çağıran sayfayı yeniliyor
break;
case 2: //islemler
hiddenField.value = "hello world 2";
window.opener.__doPostBack('' + updatePanelId + '', '');
break;
case 3: //hizmet listesi
hiddenField.value = "hello world 3";
window.opener.__doPostBack('' + updatePanelId + '', '');
break;
default:
alert("error");
break;
}
}
</script>
C#:
Session["sayfaTuru"] = 2; // initialize for testing purposes
int i = Convert.ToInt32(Session["sayfaTuru"]);
string script = string.Format("f2({0}, '{1}', '{2}');",
i.ToString(),
this.HiddenField1.ClientID,
this.GridRefreshPanel.UniqueID);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", script, true);
console.log Output:
2, "HiddenField1", "GridRefreshPanel"
ClientScript.RegisterStartupScript takes a script definition, not an invocation.
Since you want to define the function externally, use this method instead:
ClientScript.RegisterClientScriptBlock(this.GetType(), "RefreshOpener", "MyJavaScriptFile.js", true);
To execute the JavaScript function f2 with parameter Session["sayfaTuru"] on button click, use the following (not tested):
In Page_Load, add the JavaScript file which contains the definition for f2:
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(...);
// Do other stuff
}
Then add the actual button click listener which will invoke f2:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="f2(<%=Session['sayfaTuru']%>);" />
I think you may be getting an Exception thrown in your code-behind. You're trying to concatenate strings, but i is an integer. Try this instead:
int i = Convert.ToInt32(Session["sayfaTuru"]);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2(" + i.ToString() + ")", true);
Though I would actually prefer to use String.Format:
int i = Convert.ToInt32(Session["sayfaTuru"]);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", String.Format("f2({0})", i), true);
I have a hidden variable in my .aspx page.
input type="hidden" runat="server" id="isdup"
Now in code behind i check for certain conditions and assign isdup a value accordingly. However, this may not help you much but this is what i do in code behind.
bool exist = (from n in mCDC.NCDCPoints
where n.EVENT_TYPE_ID == eventID
where n.BeginDate == begin
where n.EndDate == end
select n).Count() > 0;
try
{
if (!exist)
{
//do this before insert so the insert will have correct values
isdup.Value = "false";
SaveAllColumnFields(ref ncdc, e);
mCDC.NCDCPoints.InsertOnSubmit(ncdc);
mCDC.SubmitChanges();
//do this after insert because it wont work until the ncdc object
//has been assigned an ID
SaveAllDynamicFields(mCDC, ref ncdc, e);
mCDC.SubmitChanges();
Grid1.CurrentPageIndex = 0;
}
else
{
isdup.Value = "true";
System.Windows.Forms.MessageBox.Show(isdup.Value);
}
Now I need to access the isdup inside javascript. However the problem has been that those values are not passed and isdup is null.
var showus= document.getElementById("<%=isdup.ClientID %>").value;
alert(showus);
if(showus == "true")
{
Showduplicate();
}
So, kindly let me know the mistake i have been doing?
Hve you tried with:
var showus= document.getElementById('<%=isdup.ClientID %>').value;
update
is javascript at the end of the page?
update
try to put this code in the page:
<asp:HiddenField ID="isdup" runat="server" Value="eee"/>
<script>
var showus = document.getElementById("<%=isdup.ClientID %>").value;
alert(showus);
</script>
this works for me!
update
in page_load...
protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("clientscript"))
{
string script1 = "<script language=JavaScript>";
script1 += "var showus= document.getElementById('" + isdup.ClientID + "').value;";
script1 += "alert(showus);";
script1 += "</script>";
ClientScript.RegisterStartupScript(typeof(Page), "clientscript", script1);
}
my example:
protected void pagesTree_NodeClick(object sender, RadTreeNodeEventArgs e)
{
PageStructure page = pageService.GetPage(Guid.Parse(e.Node.Value));
this.LoadPageData(page);
isdup.Value = "xxx";
}
update
bool exist = (from n in mCDC.NCDCPoints
where n.EVENT_TYPE_ID == eventID
where n.BeginDate == begin
where n.EndDate == end
select n).Count() > 0;
if (!ClientScript.IsStartupScriptRegistered("clientscript"))
{
string script1 = "<script language=JavaScript>";
script1 += "var showus= document.getElementById('" + isdup.ClientID + "').value;";
script1 += "alert(showus);";
script1 += "</script>";
ClientScript.RegisterStartupScript(typeof(Page), "clientscript", script1);
}
try
{
if (!exist)
{
//do this before insert so the insert will have correct values
isdup.Value = "false";
SaveAllColumnFields(ref ncdc, e);
mCDC.NCDCPoints.InsertOnSubmit(ncdc);
mCDC.SubmitChanges();
//do this after insert because it wont work until the ncdc object
//has been assigned an ID
SaveAllDynamicFields(mCDC, ref ncdc, e);
mCDC.SubmitChanges();
Grid1.CurrentPageIndex = 0;
}
else
{
isdup.Value = "true";
System.Windows.Forms.MessageBox.Show(isdup.Value);
}
Try this JQuery code.
var showus= $("#<%=isdup.ClientID %>").val();
Replace your input field and try this with jquery code
UPDATED
<asp:HiddenField ID="isdup" runat="server" EnableViewState="true" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"/>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var showus = $("#<%=isdup.ClientID %>").val();
alert(showus);
if (showus == "true") {
Showduplicate();
}
});
</script>