Wrox Programmer Forums
|
BOOK: Beginning ASP.NET 4.5 : in C# and VB
This is the forum to discuss the Wrox book Beginning ASP.NET 4.5: in C# and VB by Imar Spaanjaars; ISBN: 978-1-118-31180-6
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Beginning ASP.NET 4.5 : in C# and VB section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old May 26th, 2013, 12:49 AM
Friend of Wrox
 
Join Date: May 2011
Posts: 411
Thanks: 13
Thanked 7 Times in 7 Posts
Default No validation

I tried to get your addReviewHandcoded page to try to use validation controls against the input fields and when I clicked the save button, the validation controls did not fire. I tried everything under the sun to make the validation controls to fire and it was a total non-starter. I know I set them up just fine. But they still wouldn't validate. Maybe you could try to recreate the same thing on your side of things if you like and if you want I will include the markup code so that you can see that I was doing everything properly. But this one is a really big head scratcher to say the least.
 
Old May 26th, 2013, 04:04 AM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

What's described in the book certainly does work, so there must be something in your code or configuration that's messing up the validation.

Can you post the relevant code such as markup and code behind of the page as well as web.config, Global.asax.cs and the Master page (markup and code behind). As I am sure you realize, it's almost impossible to say anything useful without seeing the code.

Cheers,

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 
Old May 26th, 2013, 02:28 PM
Friend of Wrox
 
Join Date: May 2011
Posts: 411
Thanks: 13
Thanked 7 Times in 7 Posts
Default code segments

Code:
<%@ Page Title="Add Review" Language="C#" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="true" CodeFile="AddReview.aspx.cs" Inherits="AddReview" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <style type="text/css">
        .auto-style3
        {
            width: 100%;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server">
    <table class="auto-style3">
        <tr>
            <td>
                <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Names="Arial" ForeColor="#6600FF" Text="Title"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="TitleText" runat="server" Font-Bold="True" Font-Names="Calisto MT" Font-Size="Medium" ForeColor="#000099" Width="450px"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TitleText" Display="Dynamic" ErrorMessage="Please Enter a Title"></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Names="Arial" ForeColor="#6600FF" Text="Summary"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="SummaryText" runat="server" Font-Bold="True" Font-Names="Calisto MT" Font-Size="Medium" ForeColor="#000099" TextMode="MultiLine" Width="450px"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="SummaryText" Display="Dynamic" ErrorMessage="Please Enter a Summary"></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="Body" runat="server" Font-Bold="True" Font-Names="Arial" ForeColor="#6600FF" Text="Body"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="BodyText" runat="server" Font-Bold="True" Font-Names="Calisto MT" Font-Size="Medium" ForeColor="#000099" TextMode="MultiLine" Width="450px"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="BodyText" Display="Dynamic" ErrorMessage="Please Enter body Information"></asp:RequiredFieldValidator>
            </td>
        </tr>
         <tr>
    <td>
      <asp:Label ID="Label4" runat="server" Text="Genre" Font-Bold="True" Font-Names="Arial" Font-Size="Medium" ForeColor="#6600CC"></asp:Label>
    </td>
    <td>
      <asp:DropDownList ID="GenreList" runat="server" DataSourceID="EntityDataSource1" DataTextField="Name" DataValueField="Id" Font-Bold="True" Font-Names="Arial" ForeColor="#6600CC">
      </asp:DropDownList>
      <asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=PlanetWroxEntities" DefaultContainerName="PlanetWroxEntities" EnableFlattening="False" EntitySetName="Genres">
      </asp:EntityDataSource>
    </td>
  </tr>
  <tr>
      
            <td>
                <asp:Label ID="Body1" runat="server" Font-Bold="True" Font-Names="Arial" ForeColor="#6600FF" Text="Authorized"></asp:Label>
            </td>
            <td>
                <asp:CheckBox ID="Authorized" runat="server" />
            </td>
        </tr>
        
        <tr>
            <td>&nbsp;</td>
            <td>
                <asp:Button ID="SaveButton" runat="server" OnClick="SaveButton_Click" Text="Save" BackColor="#FF99CC" Font-Bold="True" ForeColor="Blue" />
            </td>
        </tr>
    </table>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="cpClientScript" Runat="Server">
</asp:Content>
More Code
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PlanetWroxModel;

public partial class AddReview : System.Web.UI.Page
{
    int _id = -1;
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    protected void SaveButton_Click(object sender, EventArgs e)
    {
        using (PlanetWroxEntities myEntities = new PlanetWroxEntities())
        {
            Review myReview;
            if (_id == -1) // Insert new item
            {
                myReview = new Review();
                myReview.CreateDateTime = DateTime.Now;
                myReview.UpdateDateTime = myReview.CreateDateTime;
                myEntities.AddToReviews(myReview);
            }
            else // update existing item
            {
                myReview = (from r in myEntities.Reviews
                            where r.Id == _id
                            select r).Single();
                myReview.UpdateDateTime = DateTime.Now;
            }
            myReview.Title = TitleText.Text;
            myReview.Summary = SummaryText.Text;
            myReview.Body = BodyText.Text;
            myReview.GenreId = Convert.ToInt32(GenreList.SelectedValue);
            myReview.Authorized = Authorized.Checked;
            myEntities.SaveChanges();
            Response.Redirect("ReviewThanks.aspx");
        }
    }
}
Web Config
Code:
<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
  </configSections>
  <connectionStrings>
    <add name="PlanetWroxConnectionString1" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\PlanetWrox.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
    <add name="PlanetWroxEntities" connectionString="metadata=res://*/App_Code.PlanetWrox.csdl|res://*/App_Code.PlanetWrox.ssdl|res://*/App_Code.PlanetWrox.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\PlanetWrox.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient"/>
  </connectionStrings>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms"/>
  </appSettings>
  <system.web>
    <trace mostRecent="true" enabled="false" requestLimit="100" pageOutput="false" localOnly="true" />
    <customErrors mode="On" defaultRedirect="~/Errors/OtherErrors.aspx" redirectMode="ResponseRewrite">
      <error statusCode="404" redirect="~/Errors/Error404.aspx"/>
    </customErrors>
    <authentication mode="Forms"/>
    <pages theme="Monochrome">
      <controls>
        <add tagPrefix="Wrox" tagName="Banner" src="~/Controls/Banner.ascx"/>
      </controls>
    </pages>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
        <add assembly="System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
      </assemblies>
      <buildProviders>
        <add extension=".edmx" type="System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider"/>
      </buildProviders>
    </compilation>
    <httpRuntime targetFramework="4.5"/>
    <profile defaultProvider="DefaultProfileProvider">
      <properties>
        <add name="FirstName"/>
        <add name="LastName"/>
        <add name="DateOfBirth" type="System.DateTime"/>
        <add name="Bio"/>
        <add name="FavoriteGenres" type="System.Collections.Generic.List`1[System.Int32]"/>
      </properties>
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PlanetWroxConnectionString1" applicationName="/"/>
      </providers>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PlanetWroxConnectionString1" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" applicationName="/"/>
      </providers>
    </membership>
    <roleManager enabled="true" defaultProvider="DefaultRoleProvider">
      <providers>
        <add connectionStringName="PlanetWroxConnectionString1" applicationName="/" name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      </providers>
    </roleManager>
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PlanetWroxConnectionString1"/>
      </providers>
    </sessionState>
  </system.web>
  <system.net>
   <mailSettings>
      
    
      </smtp>
    </mailSettings>
  </system.net>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="NameServiceAspNetAjaxBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
    <services>
      <service name="NameService">
        <endpoint address="" behaviorConfiguration="NameServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="NameService"/>
      </service>
    </services>
  </system.serviceModel>
  <location path="Management">
    <system.web>
      <authorization>
        <allow roles="Managers"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="MyProfile.aspx">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>
  <location path="ManagePhotoAlbum.aspx">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>
  <location path="NewPhotoAlbum.aspx">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>
</configuration>
 
Old May 26th, 2013, 02:29 PM
Friend of Wrox
 
Join Date: May 2011
Posts: 411
Thanks: 13
Thanked 7 Times in 7 Posts
Default Global Asax

Code:
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Net.Mail" %>

<script RunAt="server">

  void Application_Start(object sender, EventArgs e)
  {
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition { Path = "~/Scripts/jquery-1.7.2.min.js" });
  }

  void Application_End(object sender, EventArgs e)
  {
    //  Code that runs on application shutdown

  }

  void Application_Error(object sender, EventArgs e)
  {
    if (HttpContext.Current.Server.GetLastError() != null)
    {
      Exception myException = HttpContext.Current.Server.GetLastError().GetBaseException();
      string mailSubject = "Error in page " + Request.Url.ToString();
      string message = string.Empty;
      message += "<strong>Message</strong><br />" + myException.Message + "<br />";
      message += "<strong>Stack Trace</strong><br />" + myException.StackTrace + "<br />";
      message += "<strong>Query String</strong><br />" + Request.QueryString.ToString() + "<br />";
      MailMessage myMessage = new MailMessage("[email protected]", "[email protected]", mailSubject, message);
      myMessage.IsBodyHtml = true;
      SmtpClient mySmtpClient = new SmtpClient();
      mySmtpClient.Send(myMessage);
    }
  }

  void Session_Start(object sender, EventArgs e)
  {
    // Code that runs when a new session is started

  }

  void Session_End(object sender, EventArgs e)
  {
    // Code that runs when a session ends. 
    // Note: The Session_End event is raised only when the sessionstate mode
    // is set to InProc in the Web.config file. If session mode is set to StateServer 
    // or SQLServer, the event is not raised.

  }
       
</script>
 
Old May 26th, 2013, 03:23 PM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

I experimented a bit with this and it seems that UnobtrusiveValidation combined with a ScriptManager and a jQuery ScriptReference in the frontend master page doesn't work well. Your code works fine for me when I use the Management master page but doesn't work when I use the frontend master page.

Two possible fixes:

1. Set ValidationSettings:UnobtrusiveValidationMode to None in web.config or

2. Make sure you call Page.IsValid before you insert the review (see page 332 for more details).

Note that you should always implement option 2 (regardless of option 1). That issue now came to light because client-side validation doesn't work (for some reason). You should always call Page.IsValid to prevent users with JavaScript disabled from submitting invalid data.

Cheers,

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 
Old May 26th, 2013, 03:39 PM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Another, and most likely the correct way to resolve the issue, is described here: http://jupaol.blogspot.nl/2012/09/en...tion-from.html

You need to install the mentioned NuGet packages and then update the ScriptManager by adding a number of ScriptReference elements to the <Scripts> section.

Cheers,

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!





Similar Threads
Thread Thread Starter Forum Replies Last Post
Standalone validation + web form validation morbo Struts 0 August 19th, 2008 04:02 AM
Validation using Validation Framework kalyangvd Struts 1 January 2nd, 2008 06:53 AM
Validation Sheikha General .NET 4 October 8th, 2004 04:05 AM
Validation ? dinosaur_uk VB.NET 2002/2003 Basics 2 September 15th, 2004 10:28 AM
validation pab006 Classic ASP Basics 2 November 28th, 2003 05:25 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.