I'm using a detailsview for a dialog to the user, and it seems that the viewstate is not preserved when there is an error inserting the data.
I'm using a OnInserted handler on the datasource to check if there was an exception like so:
protected void areaInsertHandler(Object sender, SqlDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
// There was an error in submitting, show the error dialog
ScriptManager.RegisterClientScriptBlock(Page, GetType(), "DialogHandler", "showError('#overlayAreas');", true);
e.ExceptionHandled = true;
}
}
Which simply calls the client side JS function:
function showError(overlayName) {
$(".msgError").css('visibility', 'visible');
$(overlayName).css('visibility', 'visible');
}
My detailsview looks something like this:
<asp:UpdatePanel ID="AreaUP" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="overlayAreas" class="overlay">
<asp:DetailsView
ID="DetailsView_Areas"
runat="server"
Visible="True"
AutoGenerateInsertButton="False"
AutoGenerateRows="False"
caption="<a style='font-weight: bold;'>Bold</a> = Required field"
CaptionAlign="Bottom"
headertext="Create new area"
EnableViewState="true"
DataKeyNames="Area_Name"
DataSourceID="AreasSource"
DefaultMode="Insert">
<Fields>
...
</Fields>
</asp:DetailsView>
</div>
<br />
<asp:Button width="200" height="30" ID="Button_CreateArea" runat="server" OnClientClick="return btnToggle('#overlayAreas')" Text="Create new area" />
</ContentTemplate>
</asp:UpdatePanel>
It all works fine, but for some reason the ASP viewstate is not preserved. Meaning that if I fill out incorrect information in the form and submit I will get the appropriate error and the dialog will still be displayed. But the fields are not filled out with my old values.
If someone could give me some pointers or help me out I'd greatly appreciate it
EDIT 10-08: Still haven't been able to solve it, any ideas at all?
basically:
avoid DetailsView_Areas.DataBind()
if (DetailsView_Areas.CurrentMode != DetailsViewMode.Insert) DetailsView_Areas.DataBind();
create the ItemInserted event for your DetailsView_Areas and put
if (e.AffectedRows < 0) e.KeepInInsertMode = true;
see http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsviewinsertedeventargs.affectedrows(v=vs.110).aspx
Related
As per AntLaC link suggestion I have tried but it is not working in my coding. please help me where i made mistake please let me know. Below is back end code
protected void txtCardHolderName1_TextChanged(object sender, EventArgs e)
{
if (txtCardHolderName1.Text.Length > 0)
{
btnNext.Enabled = true;
}
else
{
btnNext.Enabled = false;
}
}
aspx code
<asp:UpdatePanel ID="upServiceFee" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtCardHolderName1" runat="server" CssClass="txtbox" Width="220px" ValidationGroup="ServiceFee" MaxLength="100" AutoPostBack="true" AutoCompleteType="Disabled" autocomplete="off" OnTextChanged="txtCardHolderName1_TextChanged"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnNext" runat="server" CssClass="btn btnBlue btnStep" Text="Submit" OnClick="btnSubmit_Click" CausesValidation="true" ValidationGroup="ServiceFee" Enabled="false" />
You can handle TextChanged event even when you don’t use the AutoPostBack property.
you could try to change the if statement to:
if(textBox != null)
I got My answer with the help of javascript,Thank you so much for helping me. Just i put below code in postback
string var = ClientScript.GetPostBackEventReference(btnNext, "").ToString();
btnNext.Attributes.Add("onClick", "javascript :if ( Page_ClientValidate() ){this.disabled=true; this.value='Please Wait...';" + var + "};");
I have asp.net FileUpload control inside an update panel. When I click upload button, I am reading the file for some code, if code not found then I am showing ModalPopup for selecting a user from dropdown, otherwise uploading and emailing the file to user of that Code(this code is saved in Database).
If code not found,its displaying ModalPopup and removing the selected file, I want to persist the selected file after post back.
This is my code
<asp:UpdatePanel ID="UpdatePanel3" runat="server" >
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:RequiredFieldValidator ID="rfvFileupload" ValidationGroup="validate" runat="server" ErrorMessage="* required" ControlToValidate="FileUpload1"></asp:RequiredFieldValidator>
</ContentTemplate>
</asp:UpdatePanel>
and on Button Click
protected void btnupload_Click(object sender, EventArgs e)
{
//Reading the file and Checking from Database
if(codefound)
{
//Sending email to the user of the Code
}
else
{
ModalPopupExtender1.Show();
}
}
How can I persists the value of Upload control on post back?
Background::
When a file is selected using FileUpload Control ,then on postback, PostedFile property gets initialized with HttpPostedFile object for the file. Since http request cannot maintain state, so it looses it's state.
NOTE: FileUpload control will not work with asynchronous postback.So a postback is needed to get the file. One way is to set the triggers for your Upload button, i.e. <asp:PostBackTrigger > & NOT <asp:AsyncPostBackTrigger>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:FileUpload ID="fileUploadImage" runat="server"></asp:FileUpload>
<asp:Button ID="btnUpload" runat="server" Text="Upload Image"
OnClick="btnUpload_Click" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUpload" />
</Triggers>
</asp:UpdatePanel>
And your Upload button code:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (fileUpload1.HasFile)
{
fileName = fileupload1.FileName;
fileUpload1.SaveAs("~/UploadedContent/" + fileName);
}
}
TO PERSIST THE VALUE OF FILEUPLOAD CONTROL, you can store the fileupload object altogether in session and after postback retrieve the values you require from session.
protected void Page_Load(object sender, EventArgs e)
{
// store the FileUpload object in Session.
// "FileUpload1" is the ID of your FileUpload control
// This condition occurs for first time you upload a file
if (Session["FileUpload1"] == null && FileUpload1.HasFile)
{
Session["FileUpload1"] = FileUpload1;
Label1.Text = FileUpload1.FileName; // get the name
}
// This condition will occur on next postbacks
else if (Session["FileUpload1"] != null && (! FileUpload1.HasFile))
{
FileUpload1 = (FileUpload) Session["FileUpload1"];
Label1.Text = FileUpload1.FileName;
}
// when Session will have File but user want to change the file
// i.e. wants to upload a new file using same FileUpload control
// so update the session to have the newly uploaded file
else if (FileUpload1.HasFile)
{
Session["FileUpload1"] = FileUpload1;
Label1.Text = FileUpload1.FileName;
}
}
This problem is somewhat well documented, the update panel is listed as not working with certain controls.
File upload, and tree view being 2 of the biggies.
To make it work you should use Triggers/PostbackTrigger
<asp:UpdatePanel ID="UpdatePanel3" runat="server" >
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:RequiredFieldValidator ID="rfvFileupload" ValidationGroup="validate" runat="server" ErrorMessage="* required" ControlToValidate="FileUpload1" />
<asp:Buton ID="btnupload" runat="server" Text="Upload" onclick="btnupload_Click"></asp:Button>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnupload"/>
</Triggers>
</asp:UpdatePanel>
try add
$('form').attr('enctype', 'multipart/form-data');
I have a listview that populates with data. This listview is inside a user control which sits inside a page called Preferences.aspx. Today I am handling click event on each row meaning that involves posting back to server.
Now, I have to put another user control on Preferences.aspx because there are group of more settings which need to be presented separately to users. I have added the new user control inside a separate tab on the page. This new tab has to be the first one to show when user lands on Preferences.aspx.
Now the problem is that when user goes to second tab (user control with listview) and click on a row, a postback occurs. This puts the user on the first tab (newly added user control).
So I wonder how can I get click event on a row without having to postback?
Any ideas or suggestions are welcome.I am working in Asp.Net with C#.
The code is:
Markup inside the user control:
<asp:TableRow runat="server" id="trVisitor" CssClass='<%# GetRowClass() %>' >
<asp:TableCell ID="tdPicture" runat="server" Width="10" onclick='<%# GetClickPostBack(Container.ItemIndex) %>'>
<div style="margin-top:1px;">
<asp:Image ImageUrl=' <%# Page.ResolveUrl("~/" + Eval("Visitor.StatusImageUrl")) %>' visible='<%# historyFlag ? false : true %>' runat="server"/>
</div>
</asp:TableCell>
... and so on
Markup inside Preferences.aspx:
<ABC:ListControl runat="server" ID="visitorListControl" CanSelect="true" IsMine="true" Recurring="false" OnVisitorSelected="ListControl_VisitorSelected" />
And code behind is:
protected string GetClickPostBack(int itemIndex)
{
if (CanSelect)
//return 0.ToString();
return "javascript: " + Page.ClientScript.GetPostBackEventReference(this, VisitorRowPrefix + itemIndex) + "; return false;";
else
return string.Empty;
}
public void RaisePostBackEvent(string eventArgument)
{
if (eventArgument.StartsWith(VisitorRowPrefix))
{
HandleRowClick(Convert.ToInt32(eventArgument.Substring(VisitorRowPrefix.Length)));
}
}
private void HandleRowClick(int index)
{
int CmgVisitorId = Constants.NotConfigured;
// bool IsHistoricVisitor = false;
// Visitor HistoricVisitor = new Visitor();
// Mark only the clicked row
... and so on.
Hook up to the grid button's click event using JavaScript/jQuery, and prevent theirs default behaviour (post-back) by 2 possible means:
return false;
e.preventDefault (jQuery only)
Example (using jQuery):
$('.button').click(function(event){
event.preventDefault();
//Write your client-side logic here
});
Description: If this method is called, the default action of the event
will not be triggered.
If I am understanding the issue properly, try an update panel.
Check out the documentation here.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:TableRow runat="server" id="trVisitor" CssClass='<%# GetRowClass() %>' >
<asp:TableCell ID="tdPicture" runat="server" Width="10" onclick='<%# GetClickPostBack(Container.ItemIndex) %>'>
<div style="margin-top:1px;">
<asp:Image ImageUrl=' <%# Page.ResolveUrl("~/" + Eval("Visitor.StatusImageUrl")) %>' visible='<%# historyFlag ? false : true %>' runat="server"/>
</div>
</asp:TableCell>
</ContentTemplate>
</asp:UpdatePanel>
At the moment I have no luck trying to get the three of them to work together and i have had only luck with the updatepanel and update progress nothing the confirm button so far.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnEnter" runat="server" Text="Update" Width="180" Style="margin-left:157px;"
OnClick="btnEnter_Click"
CssClass="button-success pure-button"/>
<asp:ConfirmButtonExtender ID="ConfirmButtonExtender1" runat="server"
TargetControlID="btnEnter"
ConfirmText="Do you want to see submit?"
ConfirmOnFormSubmit="false">
</asp:ConfirmButtonExtender>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<div class="overlay"></div>
<div class="modal">
<h2>Please Wait.....</h2>
<img alt="Loading..." src="/Images/loading.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
I have used the javascript function confirm before this and have taken it out
it was just a onclientclick on the button.
OnClientClick="return confirm('Are you sure you want to submit?');"
but I need to check validation of the page first before asking to submit but I am clueless about it.
here's the behind code atm for the button.
protected void btnEnter_Click(object sender, EventArgs e)
{
if(Page.IsValid )
{
}
}
You could do this even easier and more efficient using client side like this:
you just need to add onclientclick attribute in your <asp:Button ID="btnEnter" control and remove the <asp:ConfirmButtonExtender ID="ConfirmButtonExtender1" from your code.
it would be look like this then :
<asp:Button ID="btnEnter" runat="server" Text="Update"
Width="180" Style="margin-left:157px;"
OnClick="btnEnter_Click"
CssClass="button-success pure-button"
OnClientClick="return confirm('Do you want to see submit?');"/>
and that's it!
So you DO NOT need asp:ConfirmButtonExtender anymore.
UPDATE 1
If you require to check the condition first on the code behind then you could use the code below:
protected void btnEnter_Click(object sender, EventArgs e)
{
if(Page.IsValid )
{
ScriptManager.RegisterStartupScrip(UpdatePanel1, this.GetType(),
"confirm", "return confirm('Are you sure you want to submit?');", true);
}
}
try to Validate your form using jquery then throw the confirmation dialog if the valiation succeeded .
function ValidateForm(){
//validation
if(succeeded){
return confirm('are you sure?');
}else{
return false
}
}
$(document).ready(function(){
$('#' + '<%= btnEnter.ClientID %>').click(function(){
return ValidateForm();
});
});
so basically im in a process of creating my unit project which is an eCommerce website. one of the feature that important is a watch list (ex: watch list in ebay)
now i already finish in designing and succeed in adding/removing db record but what bothers me is that the page is the delay/ page posting back for each item saved/clicked. i tried adding an update panel but there is a still delay when we click the button.
below is my copy of the code
Design
<listview>
<itemTemplate>
......
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:LinkButton ID="lnkSaved" class="btn-icon btn-white btn-star btn-radius" runat="server" CausesValidation="false" CommandName="ToggleSave">
<span></span>
<asp:Label ID="lblSaved" runat="server" Text="Save Activity" AssociatedControlID="lnkSaved"></asp:Label>
</asp:LinkButton>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="lnkSaved" />
</Triggers>
</asp:UpdatePanel>
.......
</itemtemplate>
</listview>
CodeBehind
protected void ListViewActivities_ItemCommand(object sender, ListViewCommandEventArgs e)
{
HiddenField hdnisSaved = e.Item.FindControl("hdnisSaved") as HiddenField;
HiddenField hdnActivityID = e.Item.FindControl("hdnActivityID") as HiddenField;
LinkButton lnkSaved = e.Item.FindControl("lnkSaved") as LinkButton;
Label lblSaved= e.Item.FindControl("lblSaved") as Label;
Guid userID = new MembershipHelper().GetProviderUserKey(WebSecurity.CurrentUserId);
if (Convert.ToBoolean(hdnisSaved.Value))
{
lnkSaved.Attributes.CssStyle.Clear();
if(Convert.toboolean(hdnisSaved.Value))
{
lnkSaved.Attributes.Add("Class", "btn-icon btn-white btn-radius btn-star");
lblSaved.Text ="Save";
}
else
{
lnkSaved.Attributes.Add("Class", "btn-icon btn-white btn-radius btn-starred");
lblSaved.Text ="Saved";
}
new CustomerDAC().ToggleSave(userID, Convert.ToInt32(hdnActivityID.Value,hdnisSaved.Value));
}
}
could you guys give me a direction, what should i do so a user will have a smooth experience(async prefered) when clicking this button.
You probably want to perform the action on the client side (browser side) in javascript/jquery and then sync the changes in the background, so that the user's perception is immediate but the slow part (http roundtrip to the server and persisting the data to DB) happens in the "background".