How to validate all controller before button call OnClientClick javascript event? - asp.net

When btnSave Clicked, it will call function check().
If check() return true, the page will postback and call the btnSave_Click event.
But I think it should be check the RequiredFieldValidator first before it call fucntion check().
How can I fix it?
In Default.aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="TestValidation._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<script type="text/javascript">
function check() {
return confirm("Real?");
}
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" Display="Dynamic" ValidationGroup="vldGrp">AA</asp:RequiredFieldValidator>
<asp:Button ID="btnSave" runat="server" ValidationGroup="vldGrp" Text="Save" OnClientClick="return check();" />
<asp:ValidationSummary ID="vldSum" runat="server" DisplayMode="List" ShowSummary="False" ValidationGroup="vldGrp" ShowMessageBox="True" />
</div>
</form>
</body>
</html>
In Default.aspx.vb
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
End Sub
End Class

Check for the required field validator inside the function first and then perform the operations inside the function as:
function check() {
var validation = <%= RequiredFieldValidator1.ClientID %>;
if(validation.isValid()){
return confirm("Real?");
}
}
If there are many required field validators, and you need to invoke all of those, try:
function check() {
if (Page_ClientValidate()) {
return confirm("Real?");
}
}
Or even based on the name of your ValidationGroup (incase you need to invoke only selected validators)
function check() {
if (Page_ClientValidate('your group name')) {
return confirm("Real?");
}
}
Or else you can also check for the validation on server side,
Sub ValidateBtn_Click(sender As Object, e As EventArgs)
Page.Validate()
If (Page.IsValid) Then
DoSomething()
End If
End Sub

Related

Handles clause requires a WithEvents Callback

Error in CallbackUpdateSchema.Callback
BC30506 Visual Basic AND ASP.net Handles clause requires a WithEvents variable defined in the containing type or one of its base types. Callback
Imports DevExpress.Xpo
Imports DevExpress.Data.Filtering
Imports DevExpress.Xpo.DB
Public Class UpdateSchema
Inherits System.Web.UI.Page
Dim uow As UnitOfWork
Private Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
uow = XpoHelper.GetNewUnitOfWork
End Sub
Protected Sub CallbackUpdateSchema_Callback(source As Object, e As DevExpress.Web.CallbackEventArgs) Handles CallbackUpdateSchema.Callback
uow.UpdateSchema()
uow.CreateObjectTypeRecords()
End Sub
End Class
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="UpdateSchema.aspx.vb" %>
<%# Register assembly="DevExpress.Xpo.v18.2, Version=18.2.6.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" namespace="DevExpress.Xpo" tagprefix="dx" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<dx:ASPxButton ID="ASPxButtonUpdateSchema" runat="server" AutoPostBack="False" Text="Update Schema">
<ClientSideEvents Click="function(s, e) {CallbackUpdateSchema.PerformCallback();}" />
</dx:ASPxButton>
<dx:ASPxCallback ID="CallbackUpdateSchema" runat="server" ClientInstanceName="CallbackUpdateSchema">
</dx:ASPxCallback>
</div>
</form>
</body>
</html>
Use the overridable method OnInit
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.page.oninit?view=netframework-4.8#System_Web_UI_Page_OnInit_System_EventArgs_
Events are meant for users. For sub-classing, you should use overridable methods instead.
Protected Overrides Sub OnInit(e As EventArgs)
MyBase.OnInit()
uow = XpoHelper.GetNewUnitOfWork
End Sub

GridView not changing to edit mode when EditIndex is set on RowEditing

I am using Visual Studio 2010, VB.NET, target framework .NET 4.0.
I have a GridView which I am binding to some object collection, with a CommandField column that should allow edit of the selected row.
I am setting the EditIndex property correctly in the RowEditing eventhandler.
The problem is: When I click the "Edit" link that is generated, nothing apparently happens, the row gets rendered again in "view mode", not "edit mode".
But if I do some random postback, like clicking my "doNothing" button, the row gets rendered in "edit mode" in the next postback.
I have managed to reproduce the problem in the following code:
ASPX:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="MyForm.aspx.vb" Inherits="MySandBox.MyForm" %>
<%# Register Src="MyControl.ascx" TagName="MyControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvInfrator" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:BoundField HeaderText="MyField" DataField="MyField" />
</Columns>
</asp:GridView>
<asp:Button ID="btnDoNothing" runat="server" Text="Just do a postback" />
</form>
</body>
</html>
Code Behind:
Public Class MyDto
Public Property MyField As String
End Class
Public Class MyForm
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.BindMyData()
End Sub
Private Sub BindMyData()
Dim myData As New MyDto
myData.MyField = "My field value"
Me.gvInfrator.DataSource = New MyDto() {myData}
Me.gvInfrator.DataBind()
End Sub
Protected Sub gvInfrator_RowEditing(sender As Object, e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gvInfrator.RowEditing
Me.BindMyData()
Me.gvInfrator.EditIndex = e.NewEditIndex
End Sub
End Class
Am I doing something wrong? Is this a bug in .NET Framework 4? Is there any workaround?
You need to bind your data after you set the EditIndex of your GridView.
Protected Sub gvInfrator_RowEditing(sender As Object, e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gvInfrator.RowEditing
Me.gvInfrator.EditIndex = e.NewEditIndex
Me.BindMyData()
End Sub

Gridview inside UpdatePanel on ModalDialog not updating after AsyncFileUpload

I have a GridView inside an update panel, and a AsyncFileUpload (outside the Update Panel) that I am using to upload Images. All these are in a ASPX page called using the SHOWMODALDIALOG.
What I'm tying to achieve:
1. As soon as the file upload completes, the Update Panel updates, and the gridview displays the image the user just added.
The problems I'm facing:
1. The Gridview is not refreshing, even though I have a Databind event after the file is uploaded to the database. The Update Panel is getting refreshed through the __doPostBack('UpdatePanelID',' ') in a JS called by OnClientUploadComplete (I'm checking this through a Label showing current time in the Update Panel)
2. The ModalDialog is opening a new page whenever I click on 'Save Changes' or 'Cancel' button after adding an Image. If I just open the window and click these buttons, they work fine. I did try including <base target="_self" /> in the <head>, and finally settled with window.name="xxx" onload body.
Any help is appreciated.
My code:
ASPX
<%# Page Language="VB" AutoEventWireup="false" CodeFile="RCMT0032.aspx.vb" Inherits="RCWKSHEET.RCMT0032" EnableEventValidation="false"%>
<%# Register TagPrefix="asp" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit"%>
<html>
<head>
<base target="RCMT0032" />
<title>RCMT0032</title>
<script type="text/javascript">
function readpasseddata() {
window.name = 'RCMT0032';
var rpt = window.dialogArguments;
document.getElementById("HiddenReport").value = rpt;
}
function UploadComplete(sender, args) {
__doPostBack('gvupd', '');
}
</script>
</head>
<body onload="readpasseddata()" >
<form id="Form1" method="post" runat="server" target="RCMT0032" >
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<asp:AsyncFileUpload id="BrowserHidden" Width="1" runat="server" OnClientUploadComplete="UploadComplete" OnUploadedComplete="BrowserHidden_UploadedComplete"/>
<button class="ActionButton" id="btnSave" runat="server">Save & Exit</button>
<button class="ActionButton" id="btnClose" runat="serverCancel</button>
<asp:UpdatePanel id="gvupd" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label runat="server" ID="Label1" />
<asp:GridView id="GridView1" Runat="server" AutoGenerateColumns="False"
AllowPaging="false" EnableViewState="true" datakeynames="Seq">
<Columns>
<asp:TemplateField HeaderText="Comments">
<ItemTemplate><asp:TextBox ID="comments" Enabled="true" MaxLength="249" TextMode="MultiLine" Text='<%# Eval("Comments") %>'/>
</asp:TemplateField>
<asp:TemplateField HeaderText="Picture">
<ItemTemplate><asp:HyperLink id="PictHyper" runat="server" Target="_blank" ImageUrl='<%# String.Format("RCMT0033.aspx?report={0}&seq={1}", Eval("ReportNumber"), Eval("Seq"))%>' NavigateUrl='<%# String.Format("RCMT0034.aspx?report={0}&seq={1}", Eval("ReportNumber"), Eval("Seq"))%>' /></ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate><asp:CheckBox runat="server" ID="DeleteCB" /></ItemTemplate>
</asp:TemplateField></Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
THE CODE BEHIND
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoaD
If Not IsPostBack Then
LoadData()
DataBind()
Else
With ViewState
_intReportNumber = CInt(.Item("Report"))
_strVendorNumber = CStr(.Item("VendorNumber"))
_strStatus = CStr(.Item("Status"))
End With
End If
End Sub
Public Sub LoadData()
//GET DATA INTO DATATABLE DT
GridView1.DataSource = dt
GridView1.DataBind()
Catch err As Exception
Throw err
End Try
End Sub
Protected Sub UploadData()
If BrowserHidden.PostedFile IsNot Nothing AndAlso BrowserHidden.PostedFile.FileName <> "" Then
Try
//UPLOAD STUFF
GridView1.DataBind()
Catch ex As Exception
End Try
End If
End Sub
Protected Sub btnClose_ServerClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.ServerClick
canceladd()
ScriptManager.RegisterStartupScript(Page, Me.GetType(), "onclick", "window.open('','_self',''); window.close();", True)
End Sub
Protected Sub BrowserHidden_UploadedComplete(ByVal sender As System.Object, ByVal e As AjaxControlToolkit.AsyncFileUploadEventArgs)
UploadData()
End Sub
Protected Sub gvupd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gvupd.Load
Label1.Text = DateTime.Now.ToString()
End Sub
Protected Sub btnSave_ServerClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.ServerClick
FinalizeAdd()
Page.ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "window.open('','_self',''); window.close();", True)
End Sub
For your #2 issue, I don't think you can reload/refresh the modal window with either client side or server side script. To archive the same or similar result, you can have the upload control to close the modal window and return a value to indicate reopening is needed. then in the parent window, you can use a loop to open it as needed. if user clicks on close button on modal window or the X button on top right, the modal will not be reopened because it does not sent the "reopen" value back to parent.
ParentPage.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ParentPage.aspx.cs" Inherits="WebApplication1.ParentPage" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function popModal(){
var val = window.showModalDialog('ModalChild.aspx', '', '');
while (val == "reopen") {
val = window.showModalDialog('ModalChild.aspx', '', '');
}
}
</script>
</head>
<body>
<input type='button' value='Pop Modal' onclick='popModal();' />
</body>
</html>
ModalChild.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function closeAndReOpen(){
window.returlValue = "reopen";
window.close();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server" OnClientUploadComplete="closeAndReOpen();"
OnUploadedComplete="AsyncFileUpload1_UploadedComplete" />
<input type='button' value='Close' onclick='window.close();' />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img runat="server" id="img" /></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="AsyncFileUpload1" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
ModalChild.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI.HtmlControls;
namespace WebApplication1
{
public partial class ModalChild: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadGrid();
}
}
protected void LoadGrid()
{
var files = new DirectoryInfo(Server.MapPath("Data")).GetFiles("*.png");
GridView1.DataSource = files;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var fi = e.Row.DataItem as FileInfo;
var img = e.Row.FindControl("img") as HtmlImage;
img.Src = #"Data\" + fi.Name;
}
}
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if (AsyncFileUpload1.PostedFile != null)
{
var savePath = Server.MapPath(#"Data\" + Guid.NewGuid().ToString() + ".png");
AsyncFileUpload1.SaveAs(savePath);
}
}
}
}

How to set ASP.NET control property through IIf statement

I am not sure if things have changed after .NET 2.0 because in .NET 2.0 I used to be able to set something like this:
<asp:Panel runat="server" Visible='<%#IIf(Some condition here, "true", "false") %>' />
I did this all the time to have a clean code behind.
Currently I am working with .NET 3.0 and I cannot for the life of me get this working. The condition which i am evaluating is not accessing any data binding fields but is as simple as checking the property of an object in the code behind.
Can anyone suggest how this inline-code should look?
UPDATE:
Here is an example of what i am trying to do. I swear something like this used to work in .NET 2.0 but it does not work now:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script runat="server">
protected bool IsValid() { return true; }
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label Text="123" runat="server" Visible=<%#iif(IsValid(), "true", "false")%>/>
</div>
</form>
</body>
</html>
<%# indicates that you databind the control/page. So either you do
Private Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Me.DataBind()
End Sub
or you do it in codebehind completely(what i prefer):
Private Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
MyPanel.Visble = YourCondition
End Sub
http://naspinski.net/post/inline-aspnet-tags-sorting-them-all-out-%283c25242c-3c253d2c-3c252c-3c252c-etc%29.aspx
You can use VB in markup and C# in codebehind
<%# Page Language="VB"
Sure.. Visual Studio goes crazy
<%# Page Language="VB" AutoEventWireup="true" CodeBehind="WebForm6.aspx.cs" Inherits="WebApplication1.WebForm6" %>
<asp:repeater id="rpt" runat="server">
<ItemTemplate>
<br />
<%# Container.DataItem %>
<br />
<%#IIf( CType(Container.DataItem, System.Int32) > 5 = 0, "true", "false") %>
<br />
<br />
</ItemTemplate>
</asp:repeater>
and C# in code behind
using System.Linq;
namespace WebApplication1
{
public partial class WebForm6 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
rpt.DataSource = Enumerable.Range(1, 29);
rpt.DataBind();
}
}
}
And what VS feels about it

calling vb pagemethod from ajax

Hi
I have a simple aspx file with 2 text boxes and an ajax autocomplete extender attached to textbox2
<%# Page Language="VB" AutoEventWireup="false" CodeFile="test4.aspx.vb" Inherits="test4" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
<div id="content">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox><br />
<asp:TextBox ID="TextBox2" runat="server">
</asp:TextBox>
</div>
<asp:AutoCompleteExtender ID="load_textBox2" TargetControlID="TextBox2" ServiceMethod="GetModelName"
UseContextKey="True" runat="server">
</asp:AutoCompleteExtender>
</form>
</body>
</html>
What i am trying to do is to call the pagemethod "GetModelName" form the aspx.vb to fillup the textbox2 with the relevent data
This is the aspx.vb code
Imports System.Web.Services
Partial Class test4
Inherits System.Web.UI.Page
Dim Model_Name_old As String()()
Dim mod_code As String()
Dim mod_name As String()
Dim cod_upper As Integer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
//calling webservice that retunrs a jagged array
Dim ins As New localhost_insert_model.dbModel
Model_Name_old = ins.get_Model_Name("A")
mod_code = Model_Name_old(0)
mod_name = Model_Name_old(1)
cod_upper = Model_Name_old(0).GetUpperBound(0)
End Sub
<WebMethod()>
Public Function GetModelName() As String()
Return mod_name
End Function
End Class
This not working.. How can i make it work???.
Your function should be shared:
<WebMethod()>
Public Shared Function GetModelName() As String()
Return mod_name
End Function
Check that EnablePageMethods="true" in the script manager tag.

Resources