Asp.net retrieve content from a Control - c#

I will start by telling I'm not an ASC/C# developer, this is for a homework. (i hope somebody will understand what i want :D, because i dont know exactly the terms)
I have Friends.aspx and Friends.aspx.cs
In Friends.aspx i have something like
<%# Reference Control="~/FriendBox.ascx" %>
<div class="controlcontainer clearfix friendlist_containeritems" id="divFriends" runat="server"> </div>
In Friends.aspx.cs i have this to populate divFriends:
foreach (FBUser user in list){
Control control = LoadControl("FriendBox.ascx");
FriendBox myControl = (FriendBox)control;
myControl.user = user;
divFriends.Controls.Add(myControl);
}
In my page a have a form, and divFriends is inside the form. I have a button in this form. If i just press the button, my page gets submitted and i can retrieve values from selected checkboxes. (Every control contains a checkbox)
Everithing worked fine until i tried to submit the page via Ajax (JQuery).
My problem is that even the checkboxes are on page (i can se them, select them), when i do an ajax submit i cannot access values from checkboxes.
This is the code i use to retrieve values from checkboxes:
foreach(Control ctrl in divFriends.Controls) {
var friendBox = ctrl as FriendBox;
//i can get here
if (friendBox != null)
{ //i never get here - because friendBox is allways null }
}
How can i make the content from divFriends accesible when i submit my form with Jquery?
Thanks in advance.
Edit: here is the javascript i use
$(document).ready(function () {
$('.big').click(function () {
//.big is my button
$('.big').attr('disabled', true);
var form_form = $(document).find('form');
$.ajax({
type: 'POST',
url: form_form.attr('action'),
data: form_form.serialize(),
dataType: 'json',
success: function (data) {
console.log('success');
},
complete: function (XMLHttpRequest, textStatus) {
$('.big').attr('disabled', false);
}
});
return false;
});
});
The javascript is working because i can submit data, and i can receive data back (json), when i look at the data submited i dont have the checkboxes from divFriends.

The problem appears to be asp.net state managment issue. You are only adding FriendBox one time (I'm assuming, probably with an if not page.ispostback sort of thign), and not on each page hit. Since FriendBox is added dynamically it's not surviving a postback and thus it does not exist when you try to read it.
You should add FriendBox each time the page loads, on Init before viewstate is loaded. Adding the controls during on init will allow Viewstate to track the values and will probably fix the issue.

Related

ASP.NET and AJAX Embedded HTML Modification

My project has a "HUD" on the front page that lists students that are in the process of switching course plans. It does this by doing an AJAX call to a seperate .ascx page that runs some SQL statements in C# and renders the HTML. It then delivers it back to the front page to be placed into a div named "dynamic". Here's the code on the front page that calls it:
function loadDynamic() {
var ControlName = "utilities/HUD.ascx";
$.ajax({
type: "POST",
url: "Default.aspx/Result",
data: "{controlName:'" + ControlName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('#dynamic').html(response.d);
},
failure: function (msg) {
$('#dynamic').html(msg);
}
});
}
This is done in order to facilitate multiple people working on the system and being able to get live updates (there's another script that re-calls the loadDynamic() function every 10 seconds, but that's irrelevant to this problem).
However, there can be quite a few students that are trying to change course plans at one time, so in order to save space on the page, we've decided to try putting in a "...and # more records" link (an < a > tag with a javascript call in the href) that would activate another javascript function to show a seperate list with all the students and hide the list with only the few students on it (this javascript function is located on the HUD.ascx page).
<script type="text/javascript">
function loadMorePending() {
this.document.getElementById(<% =pnlMorePending.ClientID %>).style.visibility = 'visible';
this.document.getElementById(<% =pnlPending.ClientID %>).style.visibility = 'hidden';
}
</script>
Now that you have the background, here's the problem:
The second code block shown above contains references to two asp:Panels, which contain the lists, located on the HUD.ascx page. When someone clicks the "...and more" link, it should simply hide one asp:Panel and show the other. However, when it goes to call the function, it throws a "Microsoft JScript runtime error: 'ctl01_pnlMorePending' is undefined". Upon further investigation (when looking at the html source after it's been rendered in the browser), even when the 'dynamic' div is populated with the data from the HUD.ascx page, it remains empty!
<div id="dynamic"></div>
While this would explain why the pnlMorePending couldn't be found, it doesn't give me any leads on how to rectify this. How am I supposed to reference something that doesn't exist on the page? I've tried substituting the panels for divs, but it still doesn't work. The problem, I think, lies in the fact that the script transfers over to the front page fine, but it doesn't run on the HUD.ascx page where it needs to. Is there a way to do this without having 2 different HUD.ascx pages and 2 different "loadDynamic()" functions (the second being called and populated into the 'dynamic' div when the "...and more" button is pressed)?
Sorry if it's a little hard to follow. First time posting and the problem is pretty in-depth.
You are missing quotes:
this.document.getElementById('<% =pnlMorePending.ClientID %>').style.visibility = 'visible';

Loading an ASP.Net page inside another ASP.Net page using Ajax

I managed to load a distinct page inside a div in another page using jquery ajax. The problem I am encountering is that when I click a button inside this sub page, it cause a postback to the whole parent page. How can I force it to just refresh the panel it resides in?
One more thing. I am not sure I am doing the right thing, but the parent page has its own form with runat=server settings, while the secondary page that is loaded inside the div has its own form. I cannot remove the form from the latter because it causes an error.
I have seen some asp.net ajax tutorials but they do not deal with loading sub pages that havbe their own .net controls. Can anyone guide me to some good tutorial?
Thanks!
You need to create a empty with an Id for example : ajaxDiv
Then you create a jquery script like this :
<script type="text/javascript">
// Called at the loading of a page
$(document).ready(function () {
//here you execute an ajax function
$.ajax({
url: 'the url to retrieve data as string ex : /Webservice/Test',
type: 'get',
async: true of false,
//if the request is successful, you load the content of your div with the strings you loaded
success: function (data) {
$("ajaxDiv").html(data);
}
});
});
</script>
the tips is to load your page into the ajax request.
OK, since you are using jQuery, let's set up that event manipulation.
I assume the following markup:
<button type="submit" id="mySubmitButtonId">Submit</button>
Then, on my page I have the following javascript:
$("#mySubmitButtonId").click(function(event) {
event.preventDefault();
// do here what you want to do instead including refresh of a section via ajax
});

The Event Handler of the OK button inside a Modal PopUp is not executing

Problem here is, i have a Modal PopUp Extender inside a User Control, which is called from another User Control inside a Page, inside a Master Page. The Page loads the first user control dinamically and when i want to display the modal dialog it loads the User Control into a placeholder dinamically and call the show method of the modal when the Modal Pop Up User control loads.
Inside the modal I have some TextBoxes and a Button to save some data into the database.
The problem is that the Buton onClick event doesn't fire at all. I tried adding a breakpoint in the Onload event of the Modal Control, but it doesn't get in there, oddly enough, if i place another breakpoint in Onthe load event of the Parent User Control (the one that holds the Modal PopUp) the breakpoint does stop correctly at the Parent User Control's OnLoad event. I need to use the event handler, because there's where i call the Stored Procedure to save the data into the DB.
Please note that i don't want to just close the modalpopup window, i want to validate some textboxes then save some data into the database, that's why i must us ethe event handler of the button.
Thaks for your support
Here is a function I use in an app where I need a modal dialog box. The buttons are actually generated by the Jquery code so it's guaranteed they events get fired:
$(function () {
$(".addNew").dialog({
autoOpen: false,
width: 300,
height: 300,
modal: true,
close: function (event, ui) {
},
buttons:
{
"Exclude Week": function () {
var cReason = $('#<%= ddlReasonCode.ClientID %> option:selected').text();
var Week = $('#<%= lblWeekChange.ClientID %>').text();
$.ajax(
{
type: "POST",
url: "Ajax/ExcludeWeek.aspx",
data: "week=" + Week + "&reasonCode=" + cReason,
success: function (msg) {
$('#resultDiv').text('Added to List');
},
error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
}
);
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
});
// THis is the code used to trigger the Dialog:
$(".addNew").dialog("open");
it's probably late for the given scenario, but I had the same issue after upgrading AjaxControlToolikit version on my projects.
Problem is the ModalPopupExtender property OkControlID: in the newer versions of the toolkit server side clicked button's handler won't execute, it will be run, instead, the OnOkScript client-side code.
To restore old behavior, in my case, I had to remove OkControlID property from modal popup extender declaration tag.
Hope it helps.
Somehow, taking my entire Modal Pop-Up Box outside of a <asp:UpdatePanel> I had solved the problem for me. I will say I'm not extremely familiar with update panels, but it worked!

AJAX / Postback Issue

I've been struggling for the whole weekend with unwanted postbacks.
The popup I'm working on has a button that basicaly fires a few stored procedures and then closes the pop up window.
What I wanted to achieve is to have the same result when people hit the X closing buton on the top right.
So, X button = myCloseButton.
For that I've done this.
AJAX.
$(window).unload(function(){
var dataToSend = { MethodName: 'UpdateR' };
var options =
{
data: dataToSend,
dataType: 'JSON',
type: 'POST',
};
$.ajax(options);
});
.ASPX.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ #region Ajax methods
if (Request.Form["MethodName"] == "UpdateR")
{
UpdateRegister();
return;
}
#endregion
}
}
And then UpdateRegister() executes the code that I want to execute once people leave the page.
So, the problem comes when people hit another(whatever) control inside the pop up page. The page enters the (!IsPostBack) and the AJAX method. That's understandable since I'm saying on .unload do this and that. (I've tried $(window).bind('beforeunload', function() and it's not working for the desired purpose)
Any idea on "How can I tell the page to difference when it's a closing event like X button or my control, and any other control on the page?" would be much appreciated.
Thanks.
EDIT. It's not something about serializing the form and comparing before leaving. No, it's about logins and stuff, so even if people open the pop up and close it immediately I need to get that.
Why not you create WebMethod and directly call instead of calling via Page_Load() page event.
[WebMethod]
public static string UpdateRegister()
{
// your update register script here
}
Sample call from jquery, you can call this ajax when someone click on load or unload button.
You can call ajax script when button with id "button1" clicked e.g
$(function(){
$('#button1').click(function() {
// close window
window.close();
// call ajax script to perform server side script
$.ajax({
type: "POST",
url: "Sample.aspx/UpdateRegister",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
});
In case someone gets here with an error something like this:
Answer:
All that was begin a mess in my webform was a button (an asp one). It was postbacking, so I disabled the postback via javascript and that was it. I'm now able to move forward.

Combobox / Dropdown box not updating after its data was updated

A long explanation but I believe this is a pretty simple question. I think I'm missing something here.
After selecting a user role from a dropdown menu I'm loading a partial view with users for that role into a DIV with ajax:
$.ajax({
type: 'post',
data: { id: roleId},
url: '#Url.Action("Manage","User")',
success: function (data) {
$("#user-manage").html(data);
}
});
Now, on the page I have a combobox with the list of users and a Delete button.
I highlight a user, press the Delete button and user gets deleted.
Great! It works ,however my problem is that the deleted user doesn't disappear from the Combobox list until the page is refreshed. And I can't refresh the page because that'd mean that web site user would have to start over with selecting the Role.
So, the question is how can I make the user disappear on the combobox as soon as I hit that delete button ?
Right now when the delete button is pressed the selected UserId is passed the following ajax call that deletes a selected user and returns the updated JSON user list:
function removeUser() {
var selectedUser = $("#user-combo").find(":selected").val(); //grab selected user
var selectedForRole = $("#role-id").val(); //hidden field to store selected role
$.ajax({
url:"/User/Delete", //Delete selected user and return updated Json list
data: { id: selectedUser , roleId: selectedForRole },
type: 'post',
success: function (data) {
var userList = $("#user-combo");
var listContent;
$.each(data, function (index, item) {
listContent += "<option value='" + item.Id + "'>" + item.Name + "</option>";
});
userList.html(listContent);
}
});
}
Functionally this works. The user gets deleted but I don't see it reflected on the $("#user-combo") box until I refresh the screen.
location.reload(); doesn't work for me as I don't want the web site user to go through selecting a role to see the updated list of users.
How can I make this interactive and users disappear when I delete them and appear when add them later on ?
Thank you in advance.
Edit.
Json object returned to the combobox:
return Json(roleUsers.Select(x => new
{
Id = x.Id,
Name = x.Name
}));
It is as simple as this:
$("#comboBox option[value='USER-NAME']").remove();
Put this in your removeUser(). function.
In fact the function must not olny remve the user from the remote list, but also from the DOM.
Hpe this help.
Check your callback function. Logic seems to be OK. I have just tested and replacing select's html will remove old items and add new ones. Here's a fiddle for that.
Add several console.log() calls in your success callback function. console.log(data); console.log(userList); console.log(listContent) and see if they contain the correct data... or whether they get executed at all.
For another possible cause check your roleUsers list on the server. It maybe contains the deleted user - i.e. if you pull it out from the cache and not from the database, or you do delete after the list load.

Categories