How to call a function inside a scriptcontrol from outside using javascript - c#

I look it up for a while but couldn't find the answers I'm looking for.
I'm create an new TextBox from scratch using the IScriptControl and ScriptManager.
everything works fine inside my scriptcontrol but I'm wondering how I can trigger a function inside the scriptcontrol from outside.
to give an example. Lets say I have this:
Type.registerNamespace('QuyoDevLib.Web.UI');
QuyoDevLib.Web.UI.InputBox = function (element) {
QuyoDevLib.Web.UI.InputBox.initializeBase(this, [element]);
this._element = this.get_element();
}
QuyoDevLib.Web.UI.InputBox.prototype = {
initialize: function () {
QuyoDevLib.Web.UI.InputBox.callBaseMethod(this, 'initialize');
},
dispose: function () {
QuyoDevLib.Web.UI.InputBox.callBaseMethod(this, 'dispose');
},
doSomething: function() {
//do something usefull
}
}
QuyoDevLib.Web.UI.InputBox.registerClass('QuyoDevLib.Web.UI.InputBox', Sys.UI.Control);
if (typeof (Sys) !== 'undefined')
Sys.Application.notifyScriptLoaded();
$create(QuyoDevLib.Web.UI.InputBox, null, null, null, $get("TestControl"))
How can I make this underlaying javascript work to trigger the "doSomething" function inside my scriptcontrol?
What I had in mind you see under here but this doesn't work I already tested it.
<script>
function test() {
$get("TestControl").doSomething();
}
</script>

k I looked a bit more and found my own solution.
I share it here so everyone with the same question or problem can use it.
I had to change $get into $find to make it work.
<script>
function test() {
$get("TestControl").doSomething();
}
</script>

Related

Getting Hidden Values after $(window).load method in code behind

Context:
I converted HTML Select to Multiselect checkboxes on runtime. This required that I write my javascript code on the jquery event :
$(window).load(function () {
mulDC(); //this func converts loaded HTML select to ul with checkboxes
});
Now whatever user selects/checks on the run, I need those values back in my C# code behind.
What I have already tried is,
I created Hiddenfield and used it to populate it:
$('#<%=hdnDC.ClientID %>').val(arrSelectedValues);
This is returning me empty since this piece of code is inside .load method. I cannot use document.ready.
Need help here :)
UPDATE:
Function mulDC(). If code for .multiselect (external js file) is important, I can attach that too.
function mulDC() {
$('#chkDC').multiselect({
includeSelectAllOption: true,
renderInDiv: '#accDC',
showSelectedIn: '#selDC',
showSelectedValueIn: '#selDCVal',
chkBoxesID: 'chkDC'
});
getAllValueDC();
$('#chkDC li input:checkbox').on('change', function () {
getAllValueDC()
});
function getAllValueDC() {
var sThisVal = $('#chkDC :checkbox:checked').map(function () {
return this.value + ',';
}).get();
$('#<%=hdnDC.ClientID %>').val(sThisVal);
}
}

how to pass a variable to a Page Method Success callback function

i'm using asp.net PageMethods.So here is the way i make a call to the method from javascript
function hello()
{
var a =10;
PageMethods.SaveData(JSON.stringify(basicInfo), SaveSuccessCallback, SaveFailedCallback);
}
And here is my success call back condition
function SaveSuccessCallback(response) {
//handle success code here
ShowEdit();
}
Now i wanted to handle the ShowEdit() based on a variable a which is in the hello function.
The issue is i don't know if its possible to pass a from hello to SaveSuccessCallback .
Note: i can't make a global.
You can use a closure:
var a = 10;
PageMethods.SaveData(
JSON.stringify(basicInfo),
function(response) {
SaveSuccessCallback(response);
ShowEdit(a);
}, SaveFailedCallback);
function SaveSuccessCallback(response) {
//handle success code here
}
You may prefer to make this a bit cleaner by wrapping up the closure in another method:
PageMethods.SaveData(
JSON.stringify(basicInfo), SaveSuccessCallback(10), SaveFailedCallback);
function SaveSuccessCallback(a) {
return function(response) {
//handle success code here
ShowEdit(a);
};
}

Passing prompt box value from javascript function- PostBack to c#

I'll try to do the best I can to articulate what I'm trying to do.
Let me preface by saying that I am very new to C# and ASP.NET and have minimal experience with javascript.
I have a javascript function that invokes a prompt box. The overall picture is - if input is entered - it will be saved to a column in the database.
I'm drawing a blank on passing the value from the prompt box to the PostBack in c#.
function newName()
{
var nName = prompt("New Name", " ");
if (nName != null)
{
if (nName == " ")
{
alert("You have to specify the new name.");
return false;
}
else
{
// i think i need to getElementByID here???
//document.forms[0].submit();
}
}
}
This is what I have in C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//I have other code that works here
}
else
{
//I'm totally lost here
}
}
I'm trying to figure out how to make that call for the input from the javascript function.
I've spent the last few hours looking online and in books. Been overwhelmed.
EDIT
i did a little tweeking to fit what I'm trying to do....
<asp:HiddenField ID="txtAction" runat="server" Value="" />
document.forms(0).txtAction.Value = "saveevent";
document.forms(0).submit();
trying to figure out how to insert the string into the table now.....
string nEvent = Request.Form["event"];
if (txtAction.Value == "saveevent") {
nName.Insert(); //am i on the right track?
}
Well, here's one possible way (untested but should give you the basic idea). You could place a hidden field on your form to hold the value of the prompt:
<input type="hidden" id="hiddenNameField" runat="server" value="">
Then prompt the user for the value, set it to the hidden field, and then submit your form:
document.getElementById('hiddenNameField').value = nName;
document.forms(0).submit();
Then in your code-behind you can just access hiddenNameField.Value.
if you are trying to call the method on the back side using the java script you can try using the web method approach.
for instance you have a function that will call the SendForm method
function SendForm() {
var name = $("#label").text();
PageMethods.SendForm(name,
OnSucceeded, OnFailed);
}
function OnSucceeded() {
}
function OnFailed(error) {
}
and you have the method that will be called from javascript.
[WebMethod(enableSession: true)]
public static void SendForm(string name)
{
}
<script language='Javascript'>
__doPostBack('__Page', '');
</script>
Copied from Postback using javascript
I think you need AJAX request here. I suggest usage of jQuery, since do the dogs work for you... Otherwise, you will have to implement a lot of already written general code for AJAX processing.
Something as the following one:
function PromptSomewhere(/* some args if needed*/)
{
var nName = prompt("New Name", " ");
// Do process your prompt here... as your code in JS above. Not placed here to be more readable.
// nName is used below in the AJAX request as a data field to be passed.
$.ajax({
type: "post", // may be get, put, delete also
url: 'place-the-url-to-the-page',
data {
name: nName
// You may put also other data
},
dataType: "json",
error: PromptFailed,
success: OnPromptComplete
});
}
function PromptFailed(xhr, txtStatus, thrownErr) // The arguments may be skipped, if you don't need them
{
// Request error handling and reporting here (404, 500, etc.), for example:
alert('Some error text...'); // or
alery(txtStatus); // etc.
}
function OnPromptComplete(res)
{
if(!res)
return;
if(res.code < 0)
{
// display some validation errors
return false;
}
// display success dialog, message, or whatever you want
$("div.status").html(result.message);
}
This will enable you to send dynamically data to the server with asynchronous request. Now C#:
using System.Web.Script.Serialization;
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
string nName = Request.Form["name"];
// do validation and storage of accepted value
// prepare your result object with values
result.code = some code for status on the other side
result.message = 'Some descriptive message to be shown on the page';
// return json result
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(result));
}
}
Notes: If you use ASP.NET MVC 2 or higher I think, you will be able to use JsonResult actions and Request.IsAjaxRequest (I think was the name), and many other facilities and improvements of ASP.NET - ASP.NET MVC is the new approach for creating web applications based on MVC pattern (architecture) and will replace ASP.NET Pages eventually in some time.
This is a very good resource and contains the answer to your question:
How to use __doPostBack()
Basically, call PostbackWithParameter() function from your other JS function:
<script type="text/javascript">
function PostbackWithParameter(parameter)
{
__doPostBack(null, parameter)
}
</script>
And in your code-behind, grab the value for that parameter like so:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
}

Pass variable from one function of JS to another function of JavaScript

I am calling Showmenu() JavaScript function from C# and passing one variable to this function. Now I want to use this variable in another function of JavaScript.
<script type="text/javascript" >
var strmenu;
function ShowMenu(strmenu) {
alert(strmenu);
}
alert(strmenu);
ddsmoothmenu.init({
mainmenuid: strmenu,
orientation: 'h',
classname: 'ddsmoothmenu',
contentsource: "markup")}
</script>
I am calling ShowMenu(strmenu) function in c sharp.....like
menu_Sysadmin.Attributes.Add("OnClick", "javascript:return ShowMenu('sysadmin')");
I want to use strmenu from showmenu() in ddsmoothmenu.init() as a parameter. alert shows value but when I am trying to use strmenu as globally, it is not working.
Your strmenu parameter hides the global variable. You have to rename either the global variable or the parameter of your function and perform an assignment in your function.
var menu;
function ShowMenu(strmenu) {
menu = strmenu;
}

Returning Value in JavaScript callback for jQuery

Sorry I could not find the appropriate title
Here is my problem
I am using a method which returns a string value like hh:mm(12:45)
this method is named as DeliveryTimeCalc()
I am using a jQuery timepicker to take input on my aspx page
this timepicker has to be validated by mintime
the minimum time should be the value returned by the method DeliveryTimeCalc()
this serverside method has to be called during the jQuery is initialized
so I did the below method
<script type="text/javascript">
$(document).ready(function () {
//window.onload = pageMethodConcept.callServerSideMethod;
var time = pageMethodConcept.callServerSideMethod;
alert(time);
var hm = time.split(':');
var h = hm[0]; var m = hm[1];
$("#tb_DeliveryTime").timepicker({ showPeriodLabels: false,
onHourShow: OnHourShowCallback,
onMinuteShow: OnMinuteShowCallback
});
function OnHourShowCallback(hour) {
if ((hour < h)) {
return false; // not valid
}
return true; // valid
}
function OnMinuteShowCallback(hour, minute) {
if ((hour == h) && (minute <= m)) { return false; } // not valid
return true; // valid
}
});
</script>
<script language="javascript" type="text/javascript">
pageMethodConcept = {
callServerSideMethod: function () {
PageMethods.DeliveryTimeCalc(pageMethodConcept.callback);
},
callback: function (result) {
alert(result);
//return result;
}
}
//window.onload = pageMethodConcept.callServerSideMethod;
</script>
but the problem is that it is not returning the value (hh:mm)
I am getting a alert box which contains output like
function () {
PageMethods.DeliveryTimeCalc(pageMethodConcept.callback);
}
even if I use return I am getting the same value
but if I use
window.onload = pageMethodConcept.callServerSideMethod;
I am getting a alert box which contains output like hh:mm
Please Help!
Try simply changing:
var time = pageMethodConcept.callServerSideMethod();
with trailing () : you have to assign the return value of the function to the variable, not the function itself, but:
window.onload = pageMethodConcept.callServerSideMethod;
works as expected because you're assigning an handler to an event and you have no parameters to pass along with the function: this in fact it could be written as well as:
window.onload = function() {
pageMethodConcept.callServerSideMethod();
}
Thank you guys for helping
but i have found the solution myself
Sol 1
Using Web Services
http://markitup.com/WebServices/TimeZones.asmx?op=CurrentDateTime
this is a web service in which we have to enter the name of the time zone
Ex:(India Standard Time)
Sol 2
Write a method in the pageload and in that method write your code.
When you have to return the result
place the result in a labe text and make the visibility of the label to false
(Note: You can not find the label in javascript if the visibility is set to false
So do this instead of making visibility false. style="display: none;" this does the same
but in JavaScript you can find the label)
you can find the label in javascript by using
var time = $("#lbl_time").text();
Since we coded the jquery as $(document).ready(function () the jquery will be executed only after the page load is executed
So Problem Solved
Thank You
-Krishna Thota

Categories