Update Dropdown List from Code Behind Using Javascript / JQuery - c#

I have an application with two sections.
The top section has a dropdownlist that displays all the members in the database using a code behind method on called on page load.
The bottom section has a grid where you can add / delete / edit members using JQuery.
A change in this section obviously does not rebuild the dropdownlist in the top section.
I want to run some code in the JQuery success method that updates/rebuilds the dropdownlist to reflect the newest change to a member. I would like if possible to use the same code behind method that hits the db on page_load to populate the dropdown.
Is this possible? If so, how would I go about accomplishing this?
Any help would be greatly appreciated.
[Requested Code]
.aspx file
<asp:DropDownList ID="director" runat="server"></asp:DropDownList>
jQuery success() fired on add/delete/update member grid.
.aspx.cs (code behind)
private void LoadDirectorOptions(int deptId)
{
var memberRepo = new MemberRepository();
List<Member> members = memberRepo.GetMembers(deptId);
director.DataSource = members;
director.DataTextField = "FullName";
director.DataValueField = "Id";
director.DataBind();
director.Items.Insert(0, new ListItem("<Please Select>", "0"));
}

You can not use the same code behind method since it is a server side code and the JQuery code happens on the client side unless you refresh the page after the JQuery code executed. You can grape all the members on the same web service you are providing for updating the grid.
down list. for example :
$.ajax({
// Updating the grid here and retrun all the members : it will be saved in the response
type: "Get",
url: url,
data: data,
dataType: dataType,
success: success(data)
});
function success(data)
{
//here you can get the resposne from the server
// Iterate through data and add option elements
$(".members").append("<option value=? text=?/>");
}
Most probably your data must be JSON that has all the members in your server members database table. then you can add a CSS class(members) to your drop down list and use JQuery selector to select the drop down list.
Hope this is helpful.

Should use ajax in your success call to call method. http://api.jquery.com/jQuery.ajax/

If you want to refresh the dropdown without refreshing the whole page, you need to wrap them inside an UpdatePanel. When the grid in the bottom section is changed, update the UpdatePanel so that it rebinds the dropdown. To force the UpdatePanel to update in Javascript you could use the GetPostBackEventReference method to force a postback like this:
<%= Page.ClientScript.GetPostBackEventReference(updatePanelID, "")%>

Related

Edit ViewBag based on dropdownlist selected

i have some form with dropdownlist, i want when i select that dropdownlist, the value is passed into controller without page reload, and then change that form based on value pased, without page reload too. I have search for reference like ajax, etc, but none works for me. Please help,
I have two action in controller with that view, one to show the form and one to process httppost with that form, do i have to make one more for this?
Thankyou
What you could do is use an Ajax:
-It's be better to use MVC API controller. (Read about Api controller)
-If you want to use the controller then add the path to the routing table
Example:
-Your dropdown list onSelection/Change should trigger your JavaScript function.
-Your javaScript function should contain the following:
-(Read about how to pass json Objects around).
var json = { //You will use json to send your selected value to your controller or api
selectedValue: SelectedValue
}
$.post("//Path for controller/FolderName/Controller/MethodName", json, function (data) {
//Code after data received
if(data.success == true){//display message etc)
});
Alternative:
Create another page with the form and use razor to edit the form.
You could try the $get function in Jquery.
On change event of the drop down you can call a javaScript method to use $get:
Example
$.get(url, function (data) {
$YourDiv.html(data); //re-insert the form into the page
}
https://api.jquery.com/jquery.get/

Update collection without postback

In my application i am showing a list of records in a grid and each record has a link to update the status of the record. This grid resides inside a user control.
I would like to update the collection when user clicks the link without doing the postback.
Main.aspx
[WebMethod]
public static void UpdateFRStatus(int key)
{
ManagePartnerConfigurationNew pageObj = new ManagePartnerConfigurationNew();
pageObj.UpdateFRStatusforAjax(key);
}
ucFR.ascx
public void UpdateFRStatus(int key)
{
//Code here to update the collection.
}
//Javascript for ajax call
<script>
function statusImageClick(Key) {
//ajax call to update the grid with the updated/inserted data.
$.ajax({
type: "POST",
url: 'Main.aspx/UpdateFRStatus',
data: '{key : "' + Key + '"}',
....
}
</script>
If i move the UpdateFRStatus() to Main.aspx and make it static everything works fine. but i want to keep this method inside the user control to make the code separation.
Can you please suggests me any way i can update the collection without doing the postback.
Thanks in Advance
You Will not get any reference to The Page or usercontrol without doing a postback and loading it back into state.
Pagemethods Works for pages and not usrcontrols.
you could send enough data to The pagemethod to Update The given Entry, (for example key and statusname) then Return data to Update The UI clientside
I don't think there is any way you can directly invoke UpdateFRStatus method of the User Control because it can never be exposed as the entry point for the application.
Though, for maintaining the division of labor and all that stuff, you can keep the static method in Main.aspx. You can do something like following:
[WebMethod]
public static void UpdateFRStatus(int key)
{
ucFRObject.UpdateFRStatus(key);
}
Where ucFRObject is some object of ucFR User control that you have added on Main.aspx.
Which is essentially the same as what you are doing right now.

Executing Server-Side Methods by Clicking on a DIV

I'm working on an ASP.Net project, with C#.
Usually, when I need to put Buttons that will execute some methods, I will use the ASP Controller (Button) inside a runat="server" form.
But I feel that this really limits the capabilities of my website, because when I used to work with JSP, I used jquery to reach a servlet to execute some codes and return a responseText.
I did not check yet how this is done in ASP.Net, but my question concerns controllers and the famous runat="server".
When I add a runat="server" to any HTML Element, I'm supposed to be able to manipulate this HTML element in C# (Server-Side), and this actually works, I can change the ID, set the InnerText or InnerHtml, but the thing that I can't get, is why can't I execute a method by clicking on this element?
The "onclick" attribute is for JavaScript I think, and OnServerClick doesn't seem to work as well. Is it something wrong with my codes? or this doesn't work at all?
You will have to handle the click in the div using the Jquery and call
server-side methods through JQuery
There are several way to execute server side methods by clicking on a div or anything on your page. The first is mentioned __dopostback, second is handling the click in javascript or with jQuery and calling a function in a handler or a page method in a webservice or a page method in your page behind code.
Here is the handler version:
$("#btn1").click(function() {
$.ajax({
url: '/Handler1.ashx?param1=someparam',
success: function(msg, status, xhr) {
//doSomething, manipulate your html
},
error: function() {
//doSomething
}
});
});
I think the second version is better, because you can make a partial postback without any updatepanel, asyncronously. The drawback is, the server side code is separated from your page behind code.
Handler:
public class Handler1: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var param1= context.Request.QueryString["param1"];
//param1 value will be "someparam"
// do something cool like filling a datatable serialize it with newtonsoft jsonconvert
var dt= new DataTable();
// fill it
context.Response.Write(JsonConvert.SerializeObject(dt));
}
}
If everything is cool, you get the response in the ajax call in the success section, and the parameter called "msg" will be your serialized JSON datatable.
You can execute a method from jquery click in server, using __doPostBack javascript function, see this threat for more details How to use __doPostBack()
Add this code in your jquery on div onclick and pass DIv id whcih call click
__doPostBack('__Page', DivID);
On page load add this code
if (IsPostBack)
{
//you will get id of div which called function
string eventargs = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(eventargs))
{
//call your function
}
}
Make the div runat="server" and id="divName"
in page_Load event in cs:
if (IsPostBack)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "divClick")
{
//code to run in click event of divName
}
}
divName.Attributes.Add("ondivClick", ClientScript.GetPostBackEventReference(divName, "divClick"));
Hope it helps :)
if you are referring to divs with runat="server" attributes, they don't have onserverclick events, that's why it doesn't work

asp:dropdownlist change dynamically

Is there any chance, when I select a row from asp:dropdownlist, dynamically change page, execute sql query and after result, change selected row in second asp:dropdownlist?
If this isn't possible only with asp.net and codebehind, please let me know how to execute SELECT-query in javascript (may be with Ajax; but I don't understand it) and change second dropdown's selected row.
Thanks!
Its a bit of a generic question because there is a couple of options that you could do plus I'm not 100% sure what you want to do. In short you could use AJAX to contact a PHP page which will do an operation on your database. A result it generated and sent back to the client. You could use JSON to hold the data that is getting sent to the browser.
All AJAX does is allow you to get data from another location based on the URI you give. I would use the JQuery library as it makes it easy to implement AJAX.
// This will trigger ajax whenever the is a change in the drop down. I am assuming the drop down class is .dropdown
$('.dropdown').change(function() {
$.ajax({
type: "POST",
url: "page_change.php",
data: { name: "about_us" }
dataType:JSON,
success: function(data) {
//The data returned from test.php is loaded in the .result tag
$('.result').html(data.html);
// If you want to change page you would execute
window.location(data.url);
}
});
});
page_change.php will then contact your database and generate JSON.
More information about JQuery AJAX here:
http://api.jquery.com/jQuery.ajax/
You will need to look at JQuery, AJAX, PHP and JSON to change data on your page.
If you just want to change page on a drop down change I suppose you could store the page name in the option id?
$('.dropdown').change(function() {
var page = $(this).attr('id');
window.location(page + ".html");
});

How to I call a javascript function on onrowcommand?

Using asp.net, c# 3.5, vs 2008.
I have an aspx gridview called gv1 with a working c# codebehind onrowcommand method which is called when a button on the row is clicked.
The button on the gridview is being dynamically generated.
I am trying to replace that codebehind call with a javascript function to avoid a roundtrip to the server.
How do I do this?
So far I have tried
adding a row attribute in the code behind when I am dynamically generating the button in a foreach loop , which didnt work:
r.Attributes.Add("OnRowCommand", "javascript:gv1RowCommand(ID);");
the following which gives an error before running: no overloaded method takes 1 arg
<asp:GridView ID="gv1" runat="server" onrowcommand="gv1RowCommand(ID)" ...
various other things such as event onchange , onselected
I am using the follow javascript just to see if I can get it to be called:
function gv1RowCommand(ID) {
alert(
"row command");
}
You need to create object of your button first and then add attributes to it.
check below code -
foreach (GridViewRow row in gv1.Rows)
{
//Creates object of button inside your gridView Row
Button btnRowCommand = (Button)row.FindControl("YourButtonName");
//Adds Attribute to button- in this case adds onclick attribute
//which will fire the
//gv1RowCommand(ID); javascript function
btnRowCommand.Attributes.Add("onclick", "gv1RowCommand('"+ ID +"');");
}
Instead of
// dont use this code
r.Attributes.Add("OnRowCommand", "javascript:gv1RowCommand(ID);");
// dont use this code
This will cause your javascript function gv1RowCommand(ID) to fire when user clicks the button inside the gridview. If you need any more information of using javascript in gridView you can mail or reply. If the above code snippet is not enough for you, you can post much more code listing and will post the proper code accordingly.
Javascript events you can fiddle with:
Javascript Events
You don't have access to any of your page methods or properties in Javascript. You don't have access to anything persistant unless you're workng with Ajax... So there's not a lot that you'd do in RowCommand that you can usefully port to the client javascript layer.

Categories

Resources