I had a form which is called contact.aspx and it has a dropdown which includes user list.
I add below line to add user.
New User
and the javascript of insertUser is below:
<script type="text/javascript">
function insertUser() {
var win = window.open('stackoverflow.aspx?t=1', 'User Insert', 'width=800,height=600');
}
</script>
And when I click "New User", stackoverflow.aspx is opened and I want to enter new user data and click save.
After clicking save buton, how can I close stackoverflow.aspx and only refresh dropdown at the contact.aspx?
You can use the following Javascript code to close child window and refresh parent(ref):
window.close();
if (window.opener && !window.opener.closed) {
window.opener.location.reload();
}
or you can do partial refresh. see here
you must stored variable in session , db or ...
and use this link.
http://forums.asp.net/t/1606853.aspx/1
Don't do this on different page, because you can't update your field from an other page. You can make ajax requests from the contact.aspx by intervals, and you can check the DB if there is a new user, and refresh it. But it's not a nice solution. So I suggest to make this registration (which is on stackoverflow.aspx) on contact.aspx, inside an iframe or just inside a div. You can hide each content in each action (when you are registering, hide the rest of content just display the registration fields, if you are done refresh the dropdownlist reset your registration fields and hide them, display the dropdownlist).With this approach you can refresh your dropdownlist, when you are done with registration.
To refresh dropdownlist make an ajax call, where you can get the new values from the db (there can be multiple new values submitted by different user at the same time) and then you cen refresh dropdown (wich is a select with options in HTML) But if you do this, you can get an eventvalidation error, which is a built in asp.Net feature (defends against xss attack). So the solution can be to make a full postback after registration, and refresh the values by server code, or don't use server control to dropdownlist, only html select, and fill it on document ready, and refresh it async by javascript or jQuery.
mmm, On the stackoverflow.aspx after user clicks save, it posts to the server, creates a new user and get a JSON representation of the object. then register a script to close the window and pass the json to the opener.
private btnSave_Click(object sender, EventArgs args)
{
//Save data
...
string objectJson = GetJSON(); // {"userId": 100, "name": "John Smith"}
ClientScriptManager cs = Page.ClientScript;
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript> window.opener.appendObject(" + objectJson + ") </");
cstext1.Append("script>");
cs.RegisterStartupScript(this.GetType(), "RefreshScript", cstext1.ToString());
}
On the contacts.aspx have the following script:
<script type="text/javascript">
function appendObject(json) {
var obj = JSON.parse(json); //convert json to object
//Add item to the drop down list.
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = obj.name;
try
{
// for IE earlier than version 8
x.add(option, x.options[null]);
}
catch (e)
{
x.add(option,null);
}
}
</script>
Didn't test it but I think it works.
Related
ASP.NET 4.7.2 Web Forms c# VS 2019
I am trying to use a modalpopupextender to prompt for new data for foreign key fields. Like the form itself, the MPE is built on the fly in code -- in this case the click handler for the hidden button that the Javascript fires off to build and show the MPE.
I read every single article on SO and the ASP forums and tried everything I saw there. No joy. I get the popup perfectly. Hitting OK closes the popup, but never fires the OK Event.
Here is the code:
//Building the form, we do this in OnInit:
// AJAX Update Panel
UpdatePanel PUP = new UpdatePanel()
{
ID = "PUP",
};
PlaceHolder.Controls.Add(PUP);
// HiddenField containing the field name to permit
// creating the correct modalpopup.
HiddenField HFPopupField = new HiddenField()
{
ID = "HF_POPUP"
};
PUP.ContentTemplateContainer.Controls.Add(HFPopupField);
// Create Hidden button to track the popup
Button BPopup = new Button()
{
ID = "BPOPUP",
UseSubmitBehavior = false
};
BPopup.Click += BPopup_Click;
BPopup.Attributes.Add("style", "display: none;");
PUP.ContentTemplateContainer.Controls.Add(BPopup);
// And create the background panel for the popup.
Panel PnlPopup = new Panel()
{
ID = "PNLPOPUP",
CssClass = "MpeBackground"
};
PnlPopup.Attributes.Add("style", "display: none;");
PUP.ContentTemplateContainer.Controls.Add(PnlPopup);
/// Event handler for hidden button.
protected void BPopup_Click(object sender, EventArgs e)
{
[snip -- code to get the dataset that is being filled]
UpdatePanel PUP = Placeholder.FindControlRecursive("PUP");
Table T = new Table()
{
CssClass = "PopupTbl"
};
TableRow TRTitle = new TableRow();
TableCell TCTitle = new TableCell()
{
CssClass = "PopupTitle",
ColumnSpan = 2
};
Label LPopTitle = new Label()
{
Text = [title of the popup]
};
TCTitle.Controls.Add(LPopTitle);
TRTitle.Cells.Add(TCTitle);
DataRow drData = null;
// Add Fields, and also the cancel and Add buttons
foreach (DataColumn DC in dsColumns.Tables[0].Columns)
{
TableRow TRColumn = [create a tablerow with 2 columns, a prompt and the input field]
if (TRColumn != null)
{
T.Rows.Add(TRColumn);
[snip]
}
} // end of foreach(DataColumn DC in dsColumns.Tables[0].Columns)
PnlWindow.Controls.Add(T);
TableRow TRButtons = new TableRow();
TableCell TCButtons = new TableCell()
{
ColumnSpan = 2,
CssClass="PopupButtons"
};
Button MPEBOK = new Button()
{
ID = "MPE" + sFieldName + "_MPEBOK",
Text = "OK",
CausesValidation = false,
UseSubmitBehavior = false
};
MPEBOK.Click += MPEBOK_Clicked;
TCButtons.Controls.Add(MPEBOK);
LiteralControl LCB = new LiteralControl()
{
Text = " "
};
TCButtons.Controls.Add(LCB);
//************************************************************
//*** Postback Trigger ***
//************************************************************
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger()
{
ControlID = MPEBOK.ID,
EventName = "click"
};
PUP.Triggers.Add(trigger);
//************************************************************
//*** Cancel Button ***
//************************************************************
Button MPEBuhBye = new Button()
{
ID = "MPE" + sFieldName + "_BUHBYE",
Text = "Cancel",
UseSubmitBehavior = false
};
TCButtons.Controls.Add(MPEBuhBye);
TRButtons.Cells.Add(TCButtons);
T.Rows.Add(TRButtons);
PnlPopup.Controls.Add(PnlWindow);
AjaxControlToolkit.ModalPopupExtender MPE = new AjaxControlToolkit.ModalPopupExtender()
{
ID = "MPE" + sFieldName,
PopupControlID = "PNLPOPUP",
TargetControlID = "BPOPUP",
BackgroundCssClass = "MpeBackground"
};
// Add the MPE to the UpdatePanel.
PUP.ContentTemplateContainer.Controls.Add(MPE);
// Show the modal popup extender.
MPE.Show();
}
protected void MPEBOK_Clicked(object sender, EventArgs e)
{
[snip - this never fires]
}
I cannot find out what is happening here. Can anyone see something hinky?
Thanks
John.
You can't add a server side button or inject a server side button into the page DOM.
When you drag a asp.net button onto the form, BOTH the "mypage.cs" and mypage.desinger.cs ARE updated. The wire up of the button occurs at design time, and you would have to modify mypage.desinger.cs ALSO and ADD a button event stub.
So you can't do this.
A compromise would be to also add some js and have that HTML button execute a .click() method of a hidden asp.net button you drop into that page (that would give you the post back, and the running behind of a separate button event code stub.
This event resolution occurs at compile time - not at page render time. You have to drop that button onto the page.
I suppose you could adopt a standard that you always place right below that "div" on the page the button (hidden with style=none. And then as noted, have your injected code along with some js execute a click on the hidden button. Or just have the js button code execute a __doPostback("some value") and pick this up in the page on-load event, and then call the routine (function) from on-page load event.
I think better would be to use a jQuery.UI dialog, as that dialog CAN say load + use another different web page into a “div” on the existing page. So you layout, make, and create the nice looking popup form as a separate web page. jQuery is able to remove the “form” and additonal tags out of that page load, and then inject it into the existing page. (that code would be rather hard to re-produce). so jQuery.UI is able to pop up that separate page. however, the buttons on that loaded page (into that div) of course can't really run any code behind in the current page. However, the buttons CAN run local js in the current page. Thus the actions of this injected page would be local to each page. But the popup would not be directly calling a code behind stub.
Now, to adopt jQuery.UI, then you also have to of course adopt jQuery. So that is two extra libraries you need. (but, jQuery you likely already have).
However, I suppose the whole point of using the ajax toolkit is to avoid jQuery.ui in the first place. To be fair, before jQuery.ui came along, that tool kit was REALLY impressive, and gave asp.net folks a REAL leg up on the competition. (and it tends to be MUCH less wiring up then say using jQuery.UI
So the AjaxToolkit in its heyday was impressive. Now, it of course showing its age, but I still use the kit, and this is especially the case for the AjaxFileUploader. And yes I do use the popups – even to this day. However, I find now that jQuery.UI dialogs are more flexible, and would be better in this case (because you want a on-the fly setup).
Also, having code behind buttons in even the jQuery.UI dialog, or in this case the ajax popup? Well, only the action button can run code behind. The cancel button of course will just dismiss the dialog. However, any button in the dialog that WILL run code behind? Well, that's ok, since you have a page post back, and it actually the page postback that BLOWS out the dialog anyway.
I have an ASP.NET 4.5 web app that contains a form where the user can add some data and I have a button that I want to save the data in the database.
When the user presses this button, the first thing I do is search if there already exists a record for a specific item. If there is, I want to show a confirmation box where I'm letting the user know: "This record already exists. Do you want to update it?". If the user presses YES, I want to do an UPDATE, else I will do an INSERT. The problem is with this damn confirmation box.
What I have so far:
In aspx.cs:
public void OnConfirm(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
Response.Write("YES");
}
else
{
Response.Write("NO");
}
}
In aspx I have:
<script>
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Record already exists. Do you want to update it?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
and I added a button:
<asp:Button ID="alertBtn" runat="server" OnClientClick = "Confirm()" OnClick="OnConfirm" Text="" style="display:none"/>
If I remove the style and run the app, when I click on this button it works perfectly. The confirmation box shows up, when I click YES it calls a function, when I click NO it calls another function.
But how do I click on this button from code? Nothing works!
I tried with:
1) alertBtn.Click += new EventHandler(this.OnConfirm);// doesn't do anything
2) ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "somekey", "Confirm();", true);// I was only able to run the Confirm() method, but it didn't call the OnConfirm method which is on the server.
3) Following step 2, I tried adding a call from js to c# in the Confirm() method: document.getElementById('<%=alertBtn%>).OnClick // this didn't work either
So I just want to do a Button.Click from code behind in order to trigger the Confirm() method which will open a confirmation box and after I click YES/NO, the OnConfirm method from the server should call the appropriate function based on this YES/NO value. If you have another solution besides the one with using a button, I'm open to new ideas.
Update
To better explain my problem, I added this demo link. I want to achieve the same thing without having to click on a button, just from code.
I write script like this in my .cs file :
StringBuilder script = new StringBuilder();
script.Append("<script type=\"text/javascript\"> function submitform(){");
script.Append(" document.forms['" + ((HtmlGenericControl)frm).Attributes["id"] + "'].submit();} </");
script.Append("script>");
How can i call this function in the OnClientClick of my link button ?
LinkButton hl_process = new LinkButton();
hl_process.OnClientClick = ""
Edit1:
protected Control CreateCommForm()
{
HtmlGenericControl frm = new HtmlGenericControl("form");
frm.Attributes.Add("id", "sal");
frm.Attributes.Add("method", "post");
frm.Attributes.Add("action", "https://------");
/////////////////////////////////////////
HtmlGenericControl hdn_sal_a = new HtmlGenericControl("input");
hdn_sal_a.Attributes.Add("id", "hdn_sal_a");
hdn_sal_a.Attributes.Add("name", "hdn_sal_a");
hdn_sal_a.Attributes.Add("type", "hidden");
hdn_sal_a.Attributes.Add("value", Session["emp_num"].ToString());
/////////////////////////////////////////
HtmlGenericControl hdn_sal_b = new HtmlGenericControl("input");
hdn_sal_b.Attributes.Add("id", "hdn_sal_b");
hdn_sal_b.Attributes.Add("name", "hdn_sal_b");
hdn_sal_b.Attributes.Add("type", "hidden");
hdn_sal_b.Attributes.Add("value", Session["user_name"].ToString());
frm.Controls.Add(hdn_sal_a);
frm.Controls.Add(hdn_sal_b);
column1.Controls.Add(frm);
return frm;
}
separate the concerns The Visual part your application shouldn't be affected if you move your app to java or ruby. that's what separate of concerns is.
write the client script in the client, not in the cs file:
$('#<%= hl_process.ClientID %>').click(function(){
...
$('#formId').submit();
// if the button inside the form:
this.form.submit(); // HTML5
// Or:
$(this).closest('form').submit();
// if the button not inside the form :
var class = $(this).attr('class');
$('form.' + class).submit();
});
Use jquery to bind to the click event instead of doing this on the server side:
Submit Me
then in javascript something like:
<script type="text/javascript">
$('.blah').click(function() {
document.forms[0].submit();
});
</script>
Edit:
While you can generate UI elements with codebehind it's not quite the asp.net way. Use repeaters if you must repeat the generation of controls. Actually, creating multiple forms is not the asp.net way either, as it assumes only one form running at the server context and everything else binds to an event on submission. Anyways, it seems you're still learning asp.net and probably coming form PHP or something similar.
To accommodate your request, I'd advice to stay away from from generating JS on the server side. Give different class names to your forms and use the same method above. You don't need a LinkButton to submit the form, a simple anchor <a> fits the bill.
You can use the ClientID property (if you don't use classes), but you must first attach the parent control to the page for the algorithm to kick in.
So, your code would be something like:
protected Control CreateCommForm()
{
...
column1.Controls.Add(frm);
HtmlGenericControl a = new HtmlGenericControl("a");
a.Attributes["onclick"] = "$('#" + frm.ClientID + "').submit();";
a.InnerText = "Submit me";
frm.Controls.Add(a);
return frm;
}
The alternative way (better separation of concerns)
protected Control CreateCommForm()
{
...
column1.Controls.Add(frm);
HtmlGenericControl a = new HtmlGenericControl("a");
a.Attributes["class"] = "submitter";
a.InnerText = "Submit me";
frm.Controls.Add(a);
return frm;
}
And in javascript we find the parent form and submit it (this can be in a static js file):
<script type="text/javascript">
$('.submitter').click(function(
$(this).parents('form').submit();
));
</script>
nyone know if its possible to create a dropdown list of hyperlinks. So besides the hyperlink replacing the text field, there's also a value for each item in the list. Wondering if there's any jquery or other client side script that will let me turn my list item names into links. Using MVC2 as serverside.
Ultimately clicking on any link in the dropdown list will open a new window, this is so people can not only select a product variant but also view the details of the selected product variant in a pop-up window before submitting the form.
The hyperlink would be constructed from the items value, which is the productID and the URL that will open in a new window will just pass that as a perimeter to an action method.
Currently using this script to do the job, but I have to employ a button next to
the drop down list and its kinda ugly and confusing as you won't write too much on
a button.
function JumpToIt1(frm) {
var newPage = frm.droppa.options[frm.droppa.selectedIndex].value
if (newPage != "None") {
window.open("http://mydomain.com/category/" + newPage, "mywindow", "menubar=1,resizable=1,width=550,height=250");
}
}
$(function() {
$('#dropdownId').change(function() {
var page = $(this).val();
if (page != "None") {
window.open("http://mydomain.com/category/" + page, "mywindow", "menubar=1,resizable=1,width=550,height=250");
}
});
});
Be aware though that the new window will only open when the user selects a different value from the currently selected one. So if you remove your button the user will have no way of opening the window twice in a row without first selecting a different value.
You can have a dropdown with an onChange handler that causes it to run JavaScript whenever the dropdown changes (ie someone selects something out of the list). I think that will do what you want.
try this:
function openPopup(newPage){
if (newPage != "None") {
window.open("http://mydomain.com/category/" + newPage, "mywindow", "menubar=1,resizable=1,width=550,height=250");
}
}
$(#dropdownId").find("option").each(function(){
var $Obj= $(this);
$(this).text("<a href='javascript:void(0);' onclick='openPopup("+$Obj.val()+")'>" + $Obj.text() +"</a>");
});
So I now have the following jquery to hide or show a textbox based on specific values selected in a DropDownList. This works except that I need the first display of the popup to always be hidden. Since no index change was made in the drop down list, the following does not work for that. If I code it as visible="false", then it always stays hidden. How can I resolve this?
<script language="javascript" type="text/javascript">
var _CASE_RESERVE_ACTION = "317";
var _LEGAL_RESERVE_ACTION = "318";
function pageLoad() {
$(".statusActionDDLCssClass").change(function() {
var value = $(this).val();
if (value == _CASE_RESERVE_ACTION || value == _LEGAL_RESERVE_ACTION) {
$(".statusActionAmountCssClass").attr("disabled", false);
$(".statusActionAmountCssClass").show();
}
else {
$(".statusActionAmountCssClass").attr("disabled", true);
$(".statusActionAmountCssClass").hide();
}
});
}
</script>
Thank you,
Jim in Suwanee, GA
If you set
visible=false
.Net will not render it. You can do
style="display:none;"
and .Net will render the tag properly but CSS will hide it from the user.
Add the following to pageLoad function
function pageLoad(sender, args) {
$("input.statusActionAmountCssClass").hide();
.... rest of code .....
}
By the way, I would recommend using the selector $("input.statusActionAmountCssClass") to get a jQuery object containing a reference to your input, otherwise jQuery will search all elements to match the CSS class .statusActionAmountCssClass
EDIT:
Another change that could also be made is to use jQuery's data() to store the two global variables
$.data(window, "_CASE_RESERVE_ACTION","317");
$.data(window, "_LEGAL_RESERVE_ACTION","318");
then when you need them simply cache the value in a local variable inside the function
function someFunctionThatNeedsGlobalVariableValues() {
var caseReserveAction = $.data(window, "_CASE_RESERVE_ACTION");
var legalReserveAction = $.data(window, "_LEGAL_RESERVE_ACTION");
}
this way, the global namespace is not polluted. See this answer for more on data() command