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

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.

Related

Pass parameters to a SQL procedure in .ashx

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"]);

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..

save data in session one by one and save them altogether in database

I am sending ajax request to save model in json format in a Session
<script type="text/javascript">
$(function () {
$('#addSubject').click(function () {
var mydata = {
"SubjectId": $('#subjectid').val(),
"ObtainedGpa": $('#obtainedgpa').val(),
"SubjectTypeId": $('#subjecttypeid').val()
};
var dataToPost = JSON.stringify(mydata);
$.ajax({
type: "Post",
url: "/PreviousExamInfo/SaveSubjectInfo",
contentType: "application/json;charset=utf-8",
data: dataToPost,
dataType: "json",
});
})
});
</script>
this is done successfully.But the in my action i have to save them in Session.The approach is like "Click The ADD button and save the Values in the Session, again click the ADD button and store the new values in session with the previously stored values".And after clicking the submit button all the values which is in the session will be stored in database. How can I know that the session works as I expecting?Because wher I use
var mySession=Session["myItem"]
this only shows the new values not what I was added previously.Should I use Session? Or Is there anything else that I can use?
[HttpPost]
public JsonResult SaveSubjectInfo(PreviousExamSubject previousExamSubject)
{
List<PreviousExamSubject> list=new List<PreviousExamSubject>();
list.Add(previousExamSubject);
Session["myitem"] = list;
return Json(JsonRequestBehavior.AllowGet);
}
The code always replaces the existing Session["myitem"] with a new list. To append instead you could do something like this:
[HttpPost]
public JsonResult SaveSubjectInfo(PreviousExamSubject previousExamSubject)
{
List<PreviousExamSubject> list= (List<PreviousExamSubject>) Session["myitem"] ?? new List<PreviousExamSubject>();
list.Add(previousExamSubject);
Session["myitem"] = list;
return Json(JsonRequestBehavior.AllowGet);
}

Change Text of server Control in static Web Method

I am using a web method for ajax call, I want to change the text of my asp.net label control after ajax call.
I am changing its text on success of the ajax call,but after post back I am not getting updated value, as its changing on client side.
I want to change text so that it will reflect on post back as well.
How can I change the text of label in WebMethod?
Below is my code
[System.Web.Services.WebMethod()]
public static string RemoveVal()
{
//Do some work
//Return updated Value
//I want to change text here
}
jQuery.ajax({
type: "POST",
url: 'MyPage.aspx/RemoveVal',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var emaillbl = GetClientID("lblEmail").attr("id");
$("#" + emaillbl).html(data);
}
});
<asp:Label ID="lblEmail" runat="server" CssClass="labelclass"></asp:Label>
function GetClientID(id, context) {
var el = $("#" + id, context);
if (el.length < 1)
el = $("[id$=_" + id + "]", context);
return el;
}
AJAX call will update control text in client side only. If you want to change label's text after post back , bind the changed value again to the control while page posts back. Like you can call function which binds changed value to label in postback event OR in page load wherever seems fit.

Problem on how to update the DOM but do a check on the data with the code-behind

This is with ASP.NET Web Forms .NET 2.0 -
I have a situation that I am not sure how to fulfill all the requirements. I need to update an img source on the page if selections are made from a drop down on the same page.
Basically, the drop downs are 'options' for the item. If a selection is made (i.e. color: red) then I would update the img for the product to something like (productID_red.jpeg) IF one exists.
The problem is I don't want to do post backs and refresh the page every time a selection is made - especially if I do a check to see if the image exists before I swap out the img src for that product and the file doesn't exist so I just refreshed the entire page for nothing.
QUESTION:
So I have easily thrown some javascript together that formulates a string of the image file name based on the options selected. My question is, what options do I have to do the following:
submit the constructed image name (i.e. productID_red_large.jpg) to some where that will verify the file exists either in C# or if it is even possible in the javascript. I also have to check for different possible file types (i.e. .png, .jpg...etc.).
not do a post back and refresh the entire page
Any suggestions?
submit the constructed image name
(i.e. productID_red_large.jpg) to some
where that will verify the file exists
either in C# or if it is even possible
in the javascript. I also have to
check for different possible file
types (i.e. .png, .jpg...etc.).
not do a post back and refresh the
entire page
If you wish to not post back to the page you will want to look at $.ajax() or $.post() (which is just short hand for $.ajax() with some default options)
To handle that request you could use a Generic Http Handler.
A simple outline could work like the following:
jQuery example for the post:
$("someButton").click(function () {
//Get the image name
var imageToCheck = $("#imgFileName").val();
//construct the data to send to the handler
var dataToSend = {
fileName: imageToCheck
};
$.post("/somePath/ValidateImage.ashx", dataToSend, function (data) {
if (data === "valid") {
//Do something
} else {
//Handle error
}
}, "html");
})
Then on your asp.net side you would create an http handler that will validate that request.
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var fileName = context.Request["fileName"];
var fullPath = Path.Combine("SomeLocalPath", fileName);
//Do something to validate the file
if (File.Exists(fullPath))
{
context.Response.Write("valid");
}
else
{
context.Response.Write("invalid");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Hope this helps, if I missed the mark at all on this let me know and I can revise.
We have an app of the same type, webforms .net 2, we do something similar with the following setup:
Using jQuery you can call a method in the page behind of the current page, for example, the following will trigger the AJAX call when the select box called selectBoxName changes, so your code work out the image name here and send it to the server.
$(document).ready(function () {
$('#selectBoxName').change(function (event) {
var image_name = 'calculated image name';
$.ajax({
type: "POST",
url: 'SomePage.aspx/CheckImageName',
data: "{'imageName': '" + image_name + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function (a, b, c) {
alert("The image could not be loaded.");
}
});
});
});
Where SomePage.aspx is the current page name, and image_name is filled with the name you have already worked out. You could replace the img src in the success and error messages, again using jQuery.
The code behind for that page would then have a method like the following, were you could just reutrn true/fase or the correct image path as a string if needed. You can even return more complex types/objects and it will automatically send back the proper JSON resposne.
[System.Web.Services.WebMethod(true)]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public static bool CheckImageName(string imageName)
{
/*
* Do some logic to check the file
if (file exists)
return true;
return false;
*/
}
As it is .net 2 app, you may need to install the AJAX Extensions:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en
Could you not use a normal ajax call to the physical path of the image and check if it returns a 404?
Like this:
http://stackoverflow.com/questions/333634/http-head-request-in-javascript-ajax
<script type="text/javascript">
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status != 404;
}
function ConstructImage() {
var e = document.getElementById("opt");
var url = '[yourpath]/' + e.value + '.jpg';
if (!UrlExists(url)) {
alert('doesnt exists');
//do stuff if doesnt exist
} else {
alert('exists');
//change img if it does
}
}
</script>
<select id="opt" onchange="ConstructImage()">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>

Categories

Resources