Javascript or jQuery Gridview Filter - javascript

I have an ASP.NET GridView and multiple ListBoxes as Departments, Categories, Faculties etc. ListBoxes and GridView are filled from a database (MSSQL) in codebehind.
I need a JS or jQuery function that takes selected item's value and filters gridview rows by this value. For example, when a department selected from department listbox, it will show only the entries in that department (hide others).
I know, it is not a proper question without sample codes but i really need some hints in this case.
Thanks for help.

This might get you started.
jQuery
$("#ListBoxID").change(function() {
$("#" + GridViewID).find('td').not(':contains("' + $(this).val() + '")').parents('tr').hide();
});
Not that if your ListBox.SelectionMode is set to Multiple, $(this).val() will contain an array of selected items and you have to handle that as well.

You have a couple of options:
You could utilize jQuery Datatables (which takes your existing <table> markup that your gridview generates and powers it up with various useful options). Then you could make use of their API to add in your filtering logic. Here is an example:
http://www.datatables.net/release-datatables/examples/plug-ins/range_filtering.html
Another option is to code your own jQuery ajax call, that will fire when clicking on a list box item. It would then call a static Web Method (that returns string) in your code behind (and send the selected list box option as a parameter). Your static web method would re-query the database using the parameter value to filter the result. Then you would build a gridview in your code behind, data bind it with the query results, turn the gridview into a html string and return it as a response to your initial jQuery Ajax call. In the success: callback of your AJAX call you would grab the response html string and place it into the container html element that holds your Gridview on the page. More about this approach:
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/ (explains calling the page method with jQuery)
http://encosia.com/boost-aspnet-performance-with-deferred-content-loading/ (slightly different example, it uses ASP.NET AJAX instead of jQuery AJAX to populate html on the page - but pay attention to the static Web Method - it demonstrates how to create a html string.)
If this all seems complex, you can use regular postback (not AJAX), by creating a selected index changed event on your listbox, that will re-query the database with the filtered option and rebind the existing gridview.
Hope that this helps

Related

Dropdown based on another dropdown in jsp Struts

I'm very new to Ajax. Currently I'm working on a new project. For that project one of the requirements is, populating a second dropdown based on the input from the first dropdown. I'm using Struts to do that. I don't want the page to be refreshed, so I need to use Ajax for calling the second dropdown content in the backend and populate in the second dropdown. I don't know how to write code for that.
What should be included (jars,tags) in my struts project?
What entries should come in my JSP (I am using <html:select>)?
What will come in JavaScript?
What will come in action class (in action class I can fetch the list values from the DB based on the selection from the first dropdown)?
Instead of ajax, I used struts only to acheive this. I have assigned all variables to form to keep values when submitting form.
The answer to this question would probably a thesis ;)
I will just guide you in here.
1]Use a javascript framework like jquery. It will help you make ajax calls to your controller URL
Check an easy tutorial on http://www.tutorialspoint.com/jquery/jquery-ajax.htm
2] For the controllers lets have two urls mapped:
urapp/poplateDropdown1 to controller which return values/list target at ur first drop down
urapp/poplateDropdown2 to a another controller(or method within same controller) which responds to a GET request and receives a parameter say name SEL_VALUE for the selected value.
3] onchange events.
Have an onchange or similar best suited even on your first dropdoww.
In your event call a js function; like <select onchange=callDropDown2Controller(this.value) >
in your callDropDown2Controller() method:
//pseudo implementation
callDropDown2Controller(var selectedValue){
// now generate an AJAX get request using jquery with the following url
urlToCall = '/urapp/poplateDropdown2?SEL_VALUE=' + selectedValue
}
The rest buddy u need to do some homework and research.

Updating gridview's drop down lists using JavaScript?

I have a gridview with several fields. Fields in question are PreviousPoints, GainedPoints, TotalPoints. In the edit mode PreviousPoints is not editable, just data bind, GainedPoints is a drop down list and Total Points is a Drop Down List.
When GainedPoints drop down list selected value changes, I need the TotalPoint selected value to be set to the value of PreviousPoints control + GainedPoints selected value.
But, I cannot refresh the whole page using post back.
How can it be done using JavaScript or something similar without reloading the page?
you can use the onselect() function in javascript and have your computations there.

Add items to dropdownlist with javascript and persist in postback

I'm pretty new to web development, and I've encountered the following problem I don't really understand. Working in VS2010 with visual basic.
I have a page (aspx), which has a gridview, and this has a few columns, including a column with tickboxes and a column 'action', which has an empty, hidden dropdownlist to begin with (every row has this).
Whenever a user ticks a box, I retrieve some values from the server with an AJAX-call (which is my first attempt at AJAX :-)) and with those values I populate a dropdownlist in the 'action' colum of the selected row. So far so good.
The user can then make a selection on the dropdownlist, en then he presses a button (upload), and a postback is done to process the information.
However, in the code behind, I can't retrieve the added items in the dropdownlist (let alone the selected value). I CAN retrieve the dropdownlist, but it has no items.
After googling for some time I realised that client-side changes are not persisted when the form is posted to the server, which I understand- but it also seems odd. The dropdown is created when the page is created, so why doesn't it store the javascipt-added items? Especially since a few work-arounds I found use a hiddenfield to store the added items or selectedvalue. If I can store them in a hiddenfield, why can't I store them in the actual dropdownlist?
I'm obviously not understanding how websites work... But this means that, after a page is initially loaded, you can change values in dropdowns and listboxes and such, but these will never be available serverside?
Edit: some code; the first a javascript-snippet how I add the different values I retrieved through the AJAX call:
var drop = row.findElement("ddlAction"); //find the dropdownelement in the DOM
for (j = 0; j < dropdownitems.length; j++) { //add all the options from xml
option = document.createElement("option");
option.text = dropdownitems[i].getAttribute("text");
option.value = dropdownitems[i].getAttribute("value");
drop.add(option, null);
}
This works fine, the dropdownlist is filled and I can select. But when the page gets posted I do the following in the server code:
Dim SelCount As Integer = LocalFilesGrid.SelectedItems.Count
If SelCount >= 0 Then
For Each dataItem In LocalFilesGrid.SelectedItems
Dim drop As DropDownList
drop = dataItem.FindControl("ddlAction")
If drop.Items.Count = 0 Then 'always zero
MsgBox("Nope")
End If
Next
End If
I'd like to be able to loop through the selected rows of the grid, get the corresponding dropdownlist and selectedvalue.
When you mix such different technologies you will end up in troubles like this. What you are trying to do is bit of Ajax and a bit of ASP.NET. Choose one and then use it. If you choose ASP.NET instead of AJAX call use UpdatePanel which will simplify your life.
If you want to Ajax stuff your self, then handle the button click and submit the request by ajax rather than postback.
The reason why you are able to retrieve the drop down but not the items because you must have declared the drop down in aspx but the items were added on client side, so server has no knowledge about the items.
The reason is ASP.NET uses view state and you can not mess with view state. So you can add the data to hidden field and read them at server but you can not write the data in view state.
The best way is use ASP.NET with UpdatePanels. If you mix, then you will have to keep doing some sort of trick at every step. If you want to do your own Ajax stuff better use MVC and Razor(not mvc with aspx) because it is made for such use.

Binding dynamic select list with asp.net MVC

I have a ViewModel of a form (Name, Address) etc and it's all bound to controls on my page (using Spark engine) - e.g.
!{ Html.DropDownList() }
That works fine. However, there is one DropDownList which is bound that has no values in it to begin with, the values are populated using Ajax (by selecting previous drop downs)
The problem lies when I submit the page and there's a validation error. The page loads and my select list has no values in it (as it hasn't been triggered to get them).
How can I set it up so that the ViewModel knows about values got dynamically so that it can populate the select list on page load?
You'll either need to:
Do this server side by using the Html.DropDownList() call that allows you to pass values in:
Html.DropDownList(string name, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)
Or the other way would be to just trigger the same ajax call when the page loads so you don't have duplicated logic.
I'd actually recommend the second way, as it'll keep you from doing the same thing multiple ways, but it does mean that there'
You can add a property of selectlist type in your viewmodel, populate it in constructor, and call it through Html.DropDownList function in your view page. Further since this selectlist is dependent on another list(i.e another property of you viewmodel). in your constructor you can write code like,
say if first listbox is connected to list1 property of type int and allowed values are >0
<code>
if (list1!=0)
{
write code to populate second list based on your first list parameter and also set
the selected value as if selected by the user at submit its stored in the other
property linked to the second list box.
}
</code>
if you are still not clear, write here the concerned code of your viewmodel, and server side database call of your second list, I may help you by editing your code.

Best way to filter a list-view in asp.net MVC

I have a list of data coming from the database and displaying in a table, that works exactly how I want.
What I would like to do, is add a DropDownList to the page that "filters" the data in the table, based on the value of the selected item in the DropDonwList.
For example, the DropDown has these values
Assigned To Me
Assigned To Others
and the list of data, has an "assignedTo" field. When the value in the dropdown changes, I would like to update the list of data.
In WebForms, I would use an UpdatePanel and a DropDownList with autoPostBack=True, how can I get the same effect in MVC?
You use JavaScript/jQuery to bind to onchange/onclick event, and there do a postback:
$(function() {
$("#myelement").click(function(){
$("#secondelement").load('<%= Url.Action("Source") %>?selected=' + $(this).val());
});
}
There're jQuery plugins that do similar things, for example http://dev.chayachronicles.com/jquery/cascade/index.html (not the best one, the first I found).
You have a few options. One way is to create a Controller method that manages the process of grabbing your data (say as a IList), and then uses the Json(...) method of the Controller to serialize it and send it back as JsonResult (here's an example: http://weblogs.asp.net/mehfuzh/archive/2009/04/28/using-of-json-result-in-asp-net-mvc-1-0.aspx).
On your front end, you can wire up some javascript on the dropdown list that uses jQuery to make a $.get (http://api.jquery.com/jQuery.get/) passing back an id of sorts to determine your filter criteria.
Then you use the callback function of the $.get(...) call to manipulate your DOM as you see fit to visually depict the new list of data.

Categories

Resources