Manuell Postback in ASP.Net - asp.net

how I can do a manuell postback in the code?
I don't want a Redirect, because e.g. the user has entered values in fields in the site and decide than to login. I only want a simple Postback.

If you have link/image buttons on you page you can do:
__doPostBack('link/image button name',''); // in javascript
or if not:
var f = document.forms[0]; //if you only have one forms(this standard on asp.net)
f.__EVENTTARGET = 'some control name';
f.submit();

What's your point? Do you want to generate a postback script?
Page.ClientScript.GetPostBackEventReference(this, "Arguments", false);
Afterward, for handling the postback you must implement the System.Web.UI.IPostbackEventHandler.
But if you want a cross postback, check it out:
http://www.c-sharpcorner.com/UploadFile/DipalChoksi/xpgpostbk_asp2_dc08102006235543PM/xpgpostbk_asp2_dc.aspx

Related

ASP.net - Gridview Textbox Enter Button Postback

I have a GridView with a Textbox and when the user changes the text within that box, I want them to be able to hit the enter button and postback and update the changes they made within that textbox on the row in the GridView.
I can't figure out how to do this?
Thanks,
Mark
You need to use some JavaScript code to do that - its on the page part. Here is one that I use (jQuery)
$(document).ready(function(){
// capture the editors
var AllEditors = jQuery('#<%= gvGridViewID.ClientID %> :input[type=text]');
AllEditors.keydown(function (e) {
if (e.keyCode == 13)
{
e.preventDefault();
// the [value=Update] is the default value to Update control of GridView
jQuery(this).parents("tr").find("input[value=Update]").click();
}
});
});
If you have it inside UpdatePanel, you need to initialize it each time the UpatePanel fires. If you have it inside a custom control, you need to add extra variables on the function names to avoid conflicts.

Need to hide a section of my ASP.net webpage until user clicks submit

I have a page in ASP.net written in VB.net.
It is a series of checklists that the user will click on. When they click "SUBMIT" VBScripts will run in the background and post to a database.
I need to then get results from the database in a table.
I think I will use either GridView or ListView to do this. A requirement is when the user hits submit, the table will appear on the same page and the preexisting "SUBMIT" button will disappear.
Does this make sense? What may be the best way for me to go about this?
Currently I do not have the DB implemented but that is something I am planning to have in a week. I do have a "test" DB I can utilize.
Could you simply set the visibility of the button to false and the gridview to true during postback?
e.g.
If(Not IsPostBack) Then
{
submitButton.Visible = true; // show button
gridView.Visible = false; // hide grid
}
Else
{
submitButton.Visible = false; // user submitted, so hide button
gridView.Visible = true; // show grid
}
EndIf
You could also use the Wizard control, ask the Questions in Step 1 and return the response in Step 2. That is just an alternative, but the above is really the way to go.
In your Submit button code, after your VBScript runs you can just set the visibility of the Asp.net controls to false.
Something like this.
Private Sub btnSubmit_Click(sender As Object, e As EventArgs)
...
btnSubmit.visible = false
gridview1.visible = true
End Sub
Also on the .aspx page set these control to there default state so the submit button when the user first gets to the page should by visible, and the gridview to be not visible.
Hope this helps.

Exclude Control from Page.Isvalid

I have a few controls on a page that are all in the same validation group. Depending on certain conditions, one of these controls can be set to visible=false (and the user wont be able to input anything into it). If this happens, is there a way to remove said control from the validation group? Code like this:
if(testControl.Visible==false) testControl.ValidationGroup="";
does nothing. Yet, if I remove the validationgroup from the aspx page like so:
<asp:RequiredFieldValidator ID="testControl" runat="server" validationgroup=""></asp:RequiredFieldValidator>
The page will validate. Is there a way around this?
Are you sure your code is being hit in the code-behind file? I mean, your control is really invisible when you check that condition?
if(testControl.Visible == false)
testControl.ValidationGroup = string.Empty;
Put a breakpoint in testControl.ValidationGroup=""; and see if the debugger stops there.
Where is the code above? It should be inside the PageLoad method for example.
Call Page.Validate("NameOfYourValidationGroup") after that code.
What is the problem here I think:
You're setting this testControl with Visible = False and then you post back to the server. When you do testControl.ValidationGroup = string.Empty it'll have no effect because it has already posted back to the server:
From MSDN:
TextBox..::.ValidationGroup Property
Gets or sets the group of controls for
which the TextBox control causes
validation when it posts back to the
server.
This way you should call this code testControl.ValidationGroup = string.Empty; when you hide your control setting it to Visible = false so that when the page loads again for the user the control won't be assigned to that ValidationGroup. Now, if you postback the page it should validate the way you want it.
Set testControl.CausesValidation = false too.
Does the following help?:
testControl.IsValid = true;
Use for ex. with:
Page.Validate();
// manual override of specific control
testControl.IsValid = true;
// Guard
if (! Page.IsValid) return; // Or do own custom logic
// else
// Do your stuff here...

ASP.Net - repeating input boxes on the client side using Repeater

I have the following requirement for creating a user profile in my application:
User should be able to enter multiple phone numbers/email addresses in his profile.
The screen looks somewhat like this:
- By default, on page load a single textbox for phone and email are shown.
- User can click a "+" button to add additional numbers/addresses.
- On clicking the "+" button we need to add another textbox just below the first one. User can add as many numbers/addresses as he wants. On submit, the server should collect all numbers/emails and save it in DB.
I tried using the Repeater control to do this. On page_load I bind the repeater to a "new arraylist" object of size 1. So, this renders fine - user sees a single textbox with no value in it.
When he clicks the "+" button, I ideally want to use javascript to create more textboxes with similar mark-up as the first.
My questions are these:
Can I render the new textboxes anyway using js? I notice that the HTML rendered by the repeater control is somewhat complex (names/ids) etc. and it might not be possible to correctly create those controls on client-side.
If there is a way to do #1, will the server understand that these additional inputs are items in the repeater control? Say, I want to get all the phone numbers that the user entered by iterating over Repeater.DataItems.
Conceptually, is my approach correct or is it wrong to use the Repeater for this? Would you suggest any other approach that might handle this requirement?
Coming from a Struts/JSP background, I am still struggling to get a grip on the .NET way of doing things - so any help would be appreciated.
The repeater control may be a bit of overkill for what you're trying to accomplish. It is mainly meant as a databound control for presenting rows of data.
What you can do is to dynamically create the boxes as part of the Page_Load event (C#):
TestInput.aspx :
<form id="form1" runat="server">
<asp:HiddenField ID="hdnAddInput" runat="server" />
<asp:Button ID="btnPlus" OnClientClick="setAdd()" Text="Plus" runat="server" />
<asp:PlaceHolder ID="phInputs" runat="server" />
</form>
<script type="text/javascript">
function setAdd() {
var add = document.getElementById('<%=hdnAddInput.ClientID%>');
add.value = '1';
return true;
}
</script>
TestInput.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["inputs"] == null)
ViewState["inputs"] = 1;
if (hdnAddInput.Value == "1")
{
ViewState["inputs"] = int.Parse(ViewState["inputs"].ToString()) + 1;
hdnAddInput.Value = "";
}
for (int loop = 0; loop < int.Parse(ViewState["inputs"].ToString()); loop++)
phInputs.Controls.Add(new TextBox() { ID = "phone" + loop });
}
I ended up using a PlaceHolder to dynamically add the text boxes and a HiddenField to flag when another TextBox needed to be added. Since the IDs were matching, it maintains the ViewState of the controls during each postback.
Welcome to the hairball that is dynamically-added controls in ASP.NET. It's not pretty but it can be done.
You cannot add new fields dynamically using javascript because the new field would have no representation in the server-side controls collection of the page.
Given that the requirements are that there is no limit to the number of addresses a user can add to the page, your only option is to do "traditional" dynamic ASP.NET controls. This means that you must handle the adding of the control server-side by new-ing a new object to represent the control:
private ArrayList _dynamicControls = new ArrayList();
public void Page_Init()
{
foreach (string c in _dynamicControls)
{
TextBox txtDynamicBox = new TextBox();
txtDynamicBox.ID = c;
Controls.Add(txtDynamicBox);
}
}
public void AddNewTextBox()
{
TextBox txtNewBox = new TextBox();
txtNewBox.ID = [uniqueID] // Give the textbox a unique name
Controls.Add(txtNewBox);
_dynamicControls.Add([uniqueID]);
}
You can see here that the object that backs each dynamically-added field has to be added back to the Controls collection of the Page on each postback. If you don't do this, data POSTed back from the field has nowhere to go.
If you want to user the repeater, I think the easiest way is to put the repeater in a ASP.Net AJAX update panel, add the extra textbox on the sever side.
There are definitely other way to implement this without using repeater, and it maybe much easier to add the textbox using js.
No, but you can create input elements similar to what TextBox controls would render.
No. ASP.NET protects itself from phony data posted to the server. You can't make the server code think that it created a TextBox earlier by just adding data that it would return.
The approach is wrong. You are trying to go a middle way that doesn't work. You have to go all the way in either direction. Either you make a postback and add the TextBox on the server side, or you do it completely on the client side and use the Request.Form collection to receive the data on the server side.

Disable a button on click

I have a button control. Once the user clicks on it, the click event should fire and then the button should get disabled. How can I do this? I have the option to use JQuery or JavaScript or both.
Here is my button declaration:
<asp:Button
ID="Button1"
runat="server"
Text="Click Me"
onclick="Button1_Click"
/>
On the button click code behind, I have added a Response.Write(). That should get executed and then the button should be disabled
For whatever reason, the HTML spec dictates that disabled elements should not be included in POST requests. So, if you use JavaScript to disable the HTML element in the client-side onclick event, the input element will be disabled when the browser assembles the POST request, the server won't be properly notified which element raised the postback, and it won't fire server-side click event handlers.
When you set the UseSubmitBehavior property to false, ASP.NET renders an input element of type button instead of the regular input of type submit that the ASP.NET Button control normally generates. This is important because clicking a button element does not trigger the browser's form submit event.
Instead of relying on a browser form submission, ASP.NET will render a client-side call to __doPostBack() within that button element's onclick handler. __doPostBack will raise the postback explicitly, regardless of what POST data comes through in the request.
With the postback being raised independent of the browser submit event, you're freed of the previously mentioned HTML quirk. Then, you can set an OnClientClick of "this.disabled = true;", which will render as "this.disabled = true; __doPostBack('Button1', '');", and things will work as intended.
add an OnClientClick="this.disabled = true;" to your button.
If you are using Asp.net Ajax you might want to look at using PostBack Ritalin.
Have you tried this?
Add an OnClientClick="MyFunction();" to your .NET button.
Then in the .aspx page script tags you add the following JS function:
<script type="text/javascript">
function MyFunction()
{
window.setTimeout(function ()
{
// get the button/control to disable using your favourite clientside ...
// ... control grabbing code snippet ...
// ... eg. JQUERY $('Button1'), getElementById, etc.)
document.getElementsByName('Button1').Button1.disabled = true;
// I've used "getElementsByName" because .NET will render a button with
// ... a "name" attribute, and not an "id" attribute, by default
}, 1);
}
</script>
This gives the browser a chance to post back, followed by a quick button disable.
You need to be careful that the postback occurs before you disable the button through client script. This is a common gotcha with ajax and input boxes. Disabling an input box prevents the data from being sent from the browser, even if you can see text within it while it is disabled. The answer is that you need to use jquery for this to ensure the server-side code runs first before it is disabled.
-Oisin
// to disable
this.setAttribute('disabled', true);
// to enable
this.removeAttribute('disabled');
this is a cross browser solution
There is really cool event for body tag "<"body onBeforeunload="buttonId.disabled = true;" ">"
This event triggers right before form submits, in other words your data will be submitted correctly.
When using the "this.disabled = true" method make sure you check if the page is valid before disabling the control if you have validators on the page. If validation fails you won't be able to re-enable the control without reloading the page.
if (Page_IsValid) this.disabled = true;
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) {
document.getElementById('<%= lblMessage.ClientID %>').innerText = "Processing...";
document.getElementById('<%= btnSubmit.ClientID %>').innerText = "Processing";
args.get_postBackElement().disabled = true;
}
</script>
Add Script Tag in source page . change Id of button in code . You can disable the button till the process completes execution .
you can disable it server side
Button1.Enabled = false;

Resources