Pass parameters to a SQL procedure in .ashx - c#

I have a C# Web Forms application that is displaying a jqGrid on the home page. I struggled with the jqGrid for a while as it was returning the "jqGrid is not a function" error on any page that inherited from site.master.
To solve this, I put the code and script references for the grid in a user control and then referenced the control on the home page:
<%# Register TagPrefix="My" TagName="GridControl" Src="~/UserControls/Grid.ascx"%>
<My:GridControl ID ="gridControl" runat="server" />
Inside Grid.ascx I have the code to populate the grid which gets it's data from a stored procedure inside a handler:
<script type="text/javascript">
$(function () {
$("#dataGrid").jqGrid({
url: 'Handler1.ashx',
datatype: 'json',
I used the handler along with Newtonsoft JSON.NET to avoid the json string length error.
The stored procedure has 11 parameters which when set to NULL, return all rows, which is what I want for the initial page load.
sqlCmd.Parameters.Add("#ProjNum", SqlDbType.Int).Value = DBNull.Value;
So now, I want to filter the results based on values from dropdowns on Default.aspx. The dropdowns are populated from SQL calls as well. But my question is how to get the values from the dropdowns into my handler?
I know I can do something like url: Handler1.ashx?asgnID=19 where I've just hardcoded the value, and then get it from the context.Request.QueryString, but I still don't know how to pass the value.
I've also read about using session, and I've tried passing a json string in ajax from default.aspx in a java button click event - which didn't work because the handler ends up getting called twice. I'm a little green on this stuff, and was hoping for a better alternative.

In case anyone is having the same issue, I did the following to solve it:
Create a function to extract the parameter from the url.
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
Assign the parameter value to a variable and use it in your Jqgrid url:
$(function () {
var id = GetParameterValues('id');
$('#statusGrid').jqGrid({
url: 'Handler2.ashx?id=' + id.toString(),
datatype: 'json',
mtype: 'POST',
colNames: ['Status', 'Status Date', 'Status Time',...
And, inside the handler, extract the id from the context in ProcessRequest()
int ProjNum = Convert.ToInt32(context.Request["Id"]);

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.

How to get access drop-down control from static web method

I am trying to get access a drop-down that is in aspx page from static web method but it seems i can't get access and not what am i doing wrong. I want to set the dropdown index value to -1. thanks
this is what i am trying to do:
[System.Web.Services.WebMethod]
public static void Cancel()
{
myDDL.SelectedIndex = -1;
}
here is the javascript call
<script type="text/javascript" language="javascript">
function Func() {
//alert("hello!")
var result = confirm('WARNING');
if (result) {
//click ok button
PageMethods.Delete();
}
else {
//click cancel button
PageMethods.Cancel();
}
}
</script>
I am trying to get access a drop-down that is in aspx page from static web method
the web method in asp.net page are static, this mean are executed without page context(not completely true, you can access to Session), so what you need its retrieve result from web method, then make your update client side, something like(not tested, sorry):
jQuery.ajax({
url: 'callAJAX.aspx/Cancel',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var result = data.d.result;
$('#yourDropDownID')[0].selectedIndex = result;
}
});
It should be myDDL.selectedIndex = -1;
You cannot access a control inside webmethod..At the web service method level you cannot see anything about the page structure..
You can try this code for clearing dropdown..
Instead of calling pagemethod Cancel you can clear it inside javascript function itself..
var ddl = document.getElementById('myDDL');
ddl.options[ddl.selectedIndex] = 0;
Refer this link for extra reading..

Calling javascript function from within code using ClientScriptManager

I have the following script tag included on the _layout page of my MVC application:
<script src="https://backpack.openbadges.org/issuer.js"></script>
This is used to issue badges on completion of courses. Thus far I have been issuing badges directly from the Views using javascript such as:
var postData = {
'badgeClassID': 1
};
$.ajax({
type: "GET",
cache: false,
url: "/Admin/NewBadgeAssertion",
data: postData,
success: function (dataBA) {
var myURL = dataBA;
OpenBadges.issue([myURL]);
},
error: function (error) {
alert("An Error has occurred during the Issue of this OpenBadge");
}
});
This is working for elearning courses that I have created but the completion of SCORM courses are recorded on close of the window and I now want to issue badges for SCORM courses through C# code behind rather than from the browser view.
How can I call OpenBadges.issue([myURL]) from code behind using ClientScriptManager. I have found the RegisterStartupScript method but I am not sure how to derive the type, key and script values. I have tried this:
ClientScriptManager csm = new ClientScriptManager();
csm.RegisterStartupScript(GetType(), "msgbox", "alert('SCORM BADGE HAS BEEN ISSUED FOR SUCCESSFUL COMPLETION');", true);
But I am not correctly defining any constructors
Try this:
First, on your view page, create a simple javascript function, which does what you need it to do, such as call OpenIssues.issue:
function myFunction(myUrl)
{
alert('test:' + myUrl);
OpenBadges.issue(myUrl);
}
And in your codebehind, you can call the javascript function:
String jscript = "myFunction('" + myUrl + "')"; //sending url as parameter
Page.ClientScript.RegisterStartupScript(this.GetType(),"myscript",jscript,true);

Knockout html binding not working (bound to a function calling a partial view) in ASP .NET MVC

I have an ASP .NET MVC application, additonally I am using Knockout 2.0.0. I created a partial view which I would like to render to the page using knockout. The partial needs to be rendered within a Knockout foreach statement. I am unable to get the knockout HTML binding to work, and so I'm currently using a hack to put the html into the div using JQuery.
There is a lot of html on this page, so it's not possible to post all of the source code, so I will try and post the pertinent code:
<div data-bind="foreach:issues">
#* SNIP - A lot of other html here*#
<div id="myPartialDiv" data-bind="html: $parent.getHtml(issueId())">
</div>
</div>
Further down I have the following javascript function on my KO View Model (I have commented out my hack and included the code that returns HTML):
var getHtml = function (issueId) {
var baseUrl = '#Url.Action("GetHtmlAction","MyController")';
$.ajax(
{
type: "POST",
url: baseUrl,
data: "&issueId=" + issueId,
success: function (data) {
//$('#mypartialDiv').html(data);
return data;
},
error: function (req, status, error) {
//$('#myPartialDiv').html('Something went wrong.');
return 'Something went wrong.'
},
dataType: "text"
});
}
The code above results in no data being rendered to the page. USing Chrome debug tools, I see that there are no javascript errors occuring, and knockout is simply not binding the html of the div to the results returned from the getHtml function.
What am I doing wrong?
Thanks
As Miroslav Popovic explains, the problem is that the AJAX request is asynchronous, so the return data is ignored and there is no return value from your call to getHtml.
I would suggest using a custom binding that handles the asynchronous HTML loading (I've put a working example here).
This works by taking 2 parameters to the asyncHtml: a function to call that takes a success callback as it's final parameter (plus any other parameters) and an array of the parameters that need to be passed to that function.
<div id="myPartialDiv" data-bind="asyncHtml: { source: getHtml, params: [123] }">Loading...</div>
The custom binding then grabs these values, concats a custom callback onto the parameters that are passed to it, and calls the specified function:
ko.bindingHandlers.asyncHtml = {
init: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
var parameters = value.params.concat([function(data) {
$(element).html(data);
}]);
value.source.apply(null, parameters);
}
};
Finally we can re-implement our view model HTML-retrieving method to make the POST call and invoke the new success handler:
var ViewModel = function() {
this.getHtml = function(issueId, callback) {
$.ajax(
{
type: "POST",
url: "/echo/html/",
data: {
html: "<p>server response " + issueId + "</p>",
delay: 1
},
success: callback,
dataType: "text"
});
};
};
Note: for this example I am using the jsFiddle echo to post back a random response
$.ajax is an asynchronous call. When you call it, the execution will just continue to the next statement in the getHtml function. Since this is the last statement, the getHtml function will return undefined.
About your return data;... This return is within a success callback function. The data will be result of that function, not the parent getHtml function. Besides, getHtml is already completed. You can't return a result from it.
How about having an observable property in your view model called html, and then find some other means of triggering the getHtml function (button click, some other success callback, issueId property change...), that will in turn set the 'html' property value. Then you could simply data-bind to that property data-bind="html: html".

Grab Contents of jQuery POST call on C# Page

New to the jquery ajax methods and I am just wondering how to capture the elements passed in the jquery.ajax() call using POST on a C# (ASP.Net) page.
Here is my jquery ajax call:
$.ajax({
type: "POST",
url: 'UpdateQuickLinks.aspx',
data: {"userid": contactid, "update": addString, "remove": removeString},
success: function(){
alert('Worked');
},
error: function(){
alert('Nope');
}
});
What do i put in the C# Codebehind on the UpdateQuickLinks.aspx page to capture
userid, update, and remove strings?
Your page's Request property has a Form collection of values submitted via POST:
var form = this.Request.Form;
var userid = form["userid"];
var update = form["update"];
var remove = form["remove"];

Categories

Resources