Open jQuery UI Dialog from Code Behind - c#

I am kind of new with jQuery and JavaScript, and I ran into a problem.
I am having some problems to open the jQuery UI Dialog Box from my ButtonField within the Gridview:
<asp:ButtonField ButtonType="link" Text="Modify Deadline" Visible="true" runat="server" CommandName="modifyDeadline" ControlStyle-CssClass="button" ItemStyle-CssClass="sliderPopupOpener"/>
At first I tried to give a class to the above and named it sliderPopupOpener, and make it open the jQuery Popup when clicked as below:
$(".sliderPopupOpener").click(function () {
$("#sliderPopup").dialog("open");
});
However, this was not working because of the postback, apart from that, it also does not work with my approach. Since I would like to get some data from the database before showing the jQuery UI Dialog. So I think the best approach is to call the Dialog function from the Code Behind.
How can I do this?
I tried this approach, but it did not work, I am not sure if I am doing something wrong.
if (e.CommandName == "modifyDeadline")
{
string sliderPopupFunction = #" <script type=""text/javascript"">
$(function () {
jQuery(function () {
$(""#sliderPopup"").dialog(""open"");
}
});
</script>";
ClientScript.RegisterStartupScript(typeof(Page), "key", sliderPopupFunction);
}
Is the above possible? If so, what am I doing wrong?
EDIT:
I noticed everyone is giving their answers with a way around this, rather than telling me whether this is possible just by calling the jQuery function from the Code Behind. Although I appreciate other solutions, I would appreciate if I could get this to work, with the least effort possible, through the code behind, since I have everything ready that way.

Instead of directly bind the click event handler, you should try delegated events using live (deprecated since jquery 1.7) or on.
That way, you should change this :
$(".sliderPopupOpener").click(function () {
$("#sliderPopup").dialog("open");
});
Into something like this :
$(body).on("click", ".sliderPopupOpener", function(){
$("#sliderPopup").dialog("open");
});
alternative
If the code-behind approach is more suitable for you, you should try calling the method directly in your script, i.e, change this :
string sliderPopupFunction = #" <script type=""text/javascript"">
$(function () {
jQuery(function () {
$(""#sliderPopup"").dialog(""open"");
}
});
</script>";
into simply this :
string sliderPopupFunction = #" <script type=""text/javascript"">
$(""#sliderPopup"").dialog(""open"");
</script>";
Also, if your sliderPopup is a server-side control, you should replace the #sliderPopup with the client Id generated by ASP .NET (using sliderPopup.ClientID).
Another thing to consider is if your sliderPopup located inside the update panel, you should try re-initialize the Jquery UI dialog first, something like this :
$("#sliderPopup").dialog().dialog("open");

Just Replace the <asp:ButtonField with <asp:TemplateField the write whatever you want:
<asp:TemplateField>
<ItemTemplate>
<input type="button" onclick='jsFunctionThatShowsTheDialog()'/>
</ItemTemplate>
</asp:TemplateField>

I think in this situation it would be better for you to use a plain old <input type="button/> button and use ajax to perform your call to the server, and then with the returned data append it to your html and use the dialog. Ajax will perform your code behind without posting back your entire page.
EDIT: here is an example I did a while ago
//declaring the web method annotation allows this method to be accessed by ajax calls
//scriptmethod tells this method to take the data that we're returning, and encode it as a json so we can use it in javascript
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Person> getPeople() {
List<Person> people = null;
using (testDataEntities context = new testDataEntities()) {
people = context.People.ToList();
}
return people;
}
$(document).ready(function () {
$("#getPeople").click(function () {
$.ajax({
type: "POST",
data: {},
url: "Default.aspx/getPeople", //getPeople is the name of the method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data = msg.d;
var $table = $("<table></table>");
$.each(data,function(){
$table.append("<tr><td>"+this.MyProperty+"</td></tr>")
});
$table.dialog();
}
});
});
});

Related

Saving values of html selects and re-select them on postback

I have five dropdownlists in form of html selects. The first binds at page load using jQuery, and the rest bind when the previous dropdown has been selected. I also have five hidden fields for each dropdown which stores the selected values.
My problem is that when I do a post back, i.e. click the "Search" button, I have to re-populate the dropdowns and select the correct values again by using the ID's in the hidden fields. So far, I've come up with no good way to do this.
In the .aspx page:
<select name="boxFunktionsnedsattning" id="boxFunktionsnedsattning" multiple="multiple </select>
<asp:TextBox ID="HiddenBoxFunktionsnedsattning" runat="server" />
<script type="text/javascript">
function boxFunktionsnedsattningPopulate() {
$.ajax({
type: "POST",
url: "Sok.aspx/getFunktionsnedsattningar",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: LoadBoxFunktionsnedsattning,
failure: function (response) {
alert(response);
}
});
}
//============================================================================================================
function LoadBoxFunktionsnedsattning(response) {
var result = response.d;
var options = $("#boxFunktionsnedsattning");
options.text(''); // clear the box content before reloading
if ($('#boxFunktionsnedsattning').val != '') {
options.removeAttr("disabled");
options.multipleSelect("enable");
}
else {
options.attr("disabled", true);
options.multipleSelect("disable");
}
$.each(result, function () {
options.append($("<option />").val(this.id).text(this.name));
});
UpdateBoxEnabledState();
options.multipleSelect("refresh");
}
</script>
Backend code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Funktionsnedsattning[] getFunktionsnedsattningar()
{
GetDataService.IgetDataClient gdc = new IgetDataClient();
return gdc.getFunktionsnedsattningAll();
}
I should add that I'm a beginner when it comes to jQuery, so there is probably something I've overlooked.
IF your using webforms use an onclick function to post back to the server instead of a submit. I think this is the functionality you want because the variables in the inputs of the form will keep its value. Is the search button returning results on the same page or a different one because it will determine the ease in which you can keep varibles during a post back. Good luck!
Got it working with the following solution:
function fillFunktionsnedsattning() {
//stores the value of selected items
var $fn = $('#<%=HiddenBoxFunktionsnedsattning.ClientID%>');
//creates an array of the values in the hidden field
var fnSplit = $fn.val().split(",");
//val() accepts an array which it uses to select items in the list (go figure)
$("#boxFunktionsnedsattning").val(fnSplit);
$("#boxFunktionsnedsattning").multipleSelect("refresh");
//function that triggers the binding of the next dropdown
boxFunktionsnedsattningOnChange();
}
For it to work, this function needs to be called in the function that populates the dropdown. Each dropdown needs it's own fillFunction to be called in the same place, like this, for an example:
function LoadBoxFunktionsnedsattning(response) {
var result = response.d;
var options = $("#boxFunktionsnedsattning");
options.text(''); // clear the box content before reloading
if ($('#boxFunktionsnedsattning').val != '') {
options.removeAttr("disabled");
options.multipleSelect("enable");
}
else {
options.attr("disabled", true);
options.multipleSelect("disable");
}
$.each(result, function () {
options.append($("<option />").val(this.id).text(this.name));
});
fillFunktionsnedsattning();
UpdateBoxEnabledState();
options.multipleSelect("refresh");
It's probably possible to simplify this, but this works for me.

Can't Use PageMethod (ajax in C# .net)

I try to use PageMethod in asp.net.
First I add script Manager to my aspx page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
I wrote onClick method on JS:
function TryAJAX() {
PageMethods.TryA( onSucess, onError);
function onSucess(result) {
alert('good.');
}
function onError(result) {
alert('Something wrong.');
}
}
and in the code behind:
[WebMethod]
public static String TryA()
{
return "JSON CHECK";
}
and I always get the message 'something wrong' . althouth that in debugger I see it's enter to the methood 'TryA'.
What is the problem?
thanks!!
i know this is not the exact path you were looking to take for a solution, but I think it is a WAY better option, so here's my 2 cents...
your button in html
<input type="button" id="myStupidButton" value="Click Me Yo" />
you javascript- I am going to use jQuery too , if that is really a problem I can give you a pure js option:
<script>
$(function(){
$(document).on('click', '#myStupidButton', function(){
$.ajax({
type: "POST",
url: "Mypage.aspx/TryA",
success: function(data){
// parse asp.net's response
data = $.parseJson(data);
//asp.net wraps all json into json like this "d" : "yourresponse"
alert(data.d);
}
});
});

How to call code behind method from a javascript function?

I am having an javascript function for a HTML img click event in aspx page. And a server Method in its code behind page.Now I want to call the server method from the javascript function without any parameter only when the HTML img is clicked by the user.
C# Code Behind Method:
[WebMethod]
public void PopUpClick(object sender, EventArgs e)
{
//Something;
}
JavaScriptMethod:
$(document).ready(function () {
$('.clickme').click(function () {
PageMethods.PopUpClick();
});
});
Also I added into the master page: <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" EnablePageMethods="true" />
It is not working.When I debugging this Javascript function on the Chrome
I saw an error:Uncaught Reference Error:PageMethods is not defined.
.aspx
<div>
<p>Say bye-bey to Postbacks.</p>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" />
</div>
JavaScript
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
C#
[WebMethod]
public static string ProcessIT(string name, string address)
{
string result = "Welcome Mr. " + name + ". Your address is '" + address + "'.";
return result;
}
The WebMethods that are defined must be "static".
The following ajax call to a WebMethod "GetAllRegions" works fine, provided, the WebMethod is defined as static!!
$.ajax({
type: "POST",
url: 'GenerateEAInHtml.aspx/GetAllRegions',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
});
The WebMethod is defined this way:
[WebMethod]
public static List<Region> GetAllRegions()
{
/* Your Code goes here */
return regions;
}
You might want to use this Ajax Post to also pass JSON data to the WebMethod by passing the data parameter!! This should help.
Assumption that your page name is abc.aspx and xyz is the function name that you have to call.
javascript :
function sendData(offset) {
$.ajax({
type: "POST",
url: "abc.aspx/xyz",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
Server Side : add Imports System.Web.Script.Serialization
WebMethod(enableSession:=True) _
Public Shared Function xyz() As String
your code here
End Function
Add module in web.config -> system.webServer
->system.webServer>
->modules>
->add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
->/modules>
->/system.webServer>
Back end C# code is separate from your front end JavaScript code. JS runs on the client side and C# runs server side. In order to have front end code fire off a back end functions, you would either need your function to do a form postback or use Ajax (or an equivalent) to call that pages function.
Try this
[WebMethod]
public static void PopUpClick(object sender, EventArgs e)
{
//Something;
}
Use an ImageButton. The handler does not need to be tagged as [WebMethod]
<asp:ImageButton runat="server" ID="btnPopUp" ImageUrl="img.png" OnClick="PopUpClick" />
Why do you want to use img directly?
There is a line at the top that says uncomment this to call it by JavaScript.
Uncomment that.
Then also add a [ScriptMethod] to your method like this:
[WebMethod]
[ScriptMethod]
public void PopUpClick(object sender, EventArgs e)
{
// Something;
}
You should then be able to call it from the PageMethods object.
However I've just done some research and it seems that you may need to place your code that uses PageMethods at the end / after the ScriptManager as its possible you are trying to use PageMethods before its been declared in the JavaScript. Alternatively if you're using jQuery then you can do it in the ready event so you know the page and everything has loaded. I think this will probably turn out to be the root cause.
A web method has to be declared as static and public.
Although you can't access the page directly, you can either pass what you need into the web method from the call in your client side code, or store what you need in session or a similar state storage mechanism that is accessible from your static web method.
That may require re-thinking what you're trying to do with it.

Pass variable value calling c# behind function with javascript in asp.net

this is my scenario: I have an asp website that can merge tiff file. So, to do this i need to use a c# function and it is called after a javascript event.
The c# is like this:
public void mergeImages(string initialUrl, string lastImageUrl)
{....}
I created two hidden field like this:
<input type="hidden" id="hi1" value="D:\\ProvaUpload\\1.tif" />
to get the value to pass at the function, because I didn't know in which way I can pass js variable to it.
I call the function in this way:
'<%mergeImages(par1,par2); %>';
In which way can I pass variable value to the function?
Decorate the method with WebMethod Attribulte:
[WebMethod]
public void mergeImages(string initialUrl, string lastImageUrl)
{....}
Get the hidden fields, and pass these to Jquery Ajax call, from a button click
var hdn1 = $('#hi1').val();
var hdn2 = $('#hi2').val();
var parameters = '{initialUrl:' + hdn1 + ', lastImageUrl:' + hdn2 + '}';
$.ajax({
type: "POST",
url: "page.aspx/mergeImages",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
}
});
Refer the stackoverflow thread.
ASP.NET - Passing JSON from jQuery to ASHX
This will help you to understand to use handler file (ashx) to do ajax json request.
your requirement can be achieved with this concept.
you do not need to call cs method into javascript. you should post using ajax on any kind of handler file e.g ashx, asmx, or any other service .
Nothing to do much you just need to take an extra button which will be hide in output:
<asp:button id="btnGetAndPassvalues" runat="server" Text="hide" Onclick="btnGetAndPassvalues_Click" Style="display:none"/>
Now javascript function should be like below:
<script>
$('[id$=btnUpload]').live('click', function (e) {
// code to finish Upload prosess
$('[id$=btnGetAndPassvalues]').click();
});
</script>
That's all and in click event get the values of hidden field:
protected void btnGetAndPassvalues(Object sender,EventArgs e){
string hd1=hiden1.Value;
string hd2=hiden2.Value;
}
or you can make AJAX Call,
one of the easy way to achieve this :-
As you already have two hidden fields but must add runat attribute to it ,so that
you can get their values at server side. Let's Say:-
<input type="hidden" id="hi1" value="D:\\ProvaUpload\\1.tif" runat="server" />
<input type="hidden" id="hi2" value="D:\\ProvaUpload\\2.tif" runat="server" />
and Make a hidden button :-
<asp:button id="btnhidden" runat="server" Text="hide" Onclick="btnhidden_Click" Style="display:none"/>
Now you can click the button in javascript function :-
function UploadFinished()
{
//your JS code:-
// After finish uploading ..Click the button .. i have used jquery for simplicity:-
$('input[id$="btnhidden"]').click();
}
Now in your code behind :-
protected void btnhidden_Click(Object sender,EventArgs e)
{
// you can get hidden fields values here ....
string val1=hi1.Value;
string val2=hi2.Value;
// Call your merge function here :-
mergeImages(val1,val2);
}

Calling a web service from Javascript (passing parameters and returning dataset)

I have created a web service in C# and now need to call it from a mobile app. I'm trying to create a Windows 7 mobile app, but using HTML5 and Javascript not the native code. The web service takes 2 parameters, Email and Password, and returns a Dataset. I don't really have any javascript experience (or web services experience for that matter, trying to learn with this project), and when trying to research how to call a web service using javascript I just found too much information and didn't know where to begin because so many other technologies were also mentioned.
So I decided to try things out and this is what I came up with so far:
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
// once the device ready event fires, you can safely do your thing! -jm
function onDeviceReady() {
}
function LoginButton_onclick() {
UpdateChildrenApp.PhoneWebServices.GetMyChildren(document.getElementById('EmailBox').value,document.getElementById('PasswordBox').value, OnComplete, OnError)
}
function OnComplete(result) {
for (var i = 0; i < result.tables[0].rows.length; i++)
document.getElementById('Test').innerHTML += ''+(result.tables[0].rows[i].col_name);
}
function OnError(result) {
document.getElementById('Test').innerHTML ='Error :'+result.get_message();
}
</script>
This code does nothing when I press the submit button. Could someone please point out what the problems are and how I can fix them or suggest what I should research to address the problems and put me on the right track? Any help is greatly appreciated.
First, your webservices should return a JSON object if you want to use it in javascript.
You can of course return any XML/string, but using JSON will be A LOT easy to use the data in javascript.
Then, I would advise you to use jquery to call the webservice, as jquery will do a lot of work for you.
Read this article, it should help you set different components correctly:
I would use jQuery to do this kind of thing.
The ajax functionality its provides is really easy to use.
I would use the Revealing Module Pattern (RMP) and 2 javascript files. If you're unfamiliar with the RMP, there is a great post covering it here:
http://weblogs.asp.net/dwahlin/archive/2011/08/02/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-module-pattern.aspx
I find that if I dont employ some kind of structure to my js code using the RMP, I just end up with a mess of functions in one file.
Id have Startup.js and Dataservice.js and they would look something like this:
Startup.js
var Startup = function () {
var isValid,
dataObject = {},
populateDataObject = function () {
dataObject.dealer = $("[id$='_txtUser']").val();
dataObject.password = $("[id$='_txtPassword']").val();
},
init = function () {
var dealerId = 0;
$("[id$='_SubmitButton']").bind('click', function (evt) {
evt.preventDefault();
populateDataObject();
if (isValid) {
Dataservice.processLoginRequest(dataObject, processLoginRequestResult);
}
});
};
return {
init: init,
processLoginRequestResult: processLoginRequestResult
};
} ();
Dataservice.js (assumes old school .asmx, change as needed)
var Dataservice = function () {
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
var serviceBase = '../services/LoginService.asmx/',
processScreenRequest = function (valObject, callback) {
$.ajax({
url: serviceBase + "ProcessLoginRequest",
data: JSON.stringify(valObject),
success: function (json) {
callback(json);
}
});
};
return {
processScreenRequest: processScreenRequest
};
} ();
and then I would include refereces to these 2 js files as well as jquery in my html page.
I hope this helps.
I've used Dojo for this once, its pretty simple you can make xhrget or xhrpost requests. It has a function called load that is the callback where you can modify the contents of the HTML components in the page.
Use these links : http://dojotoolkit.org/reference-guide/1.7/dojo/xhrGet.html

Categories

Resources