alaa
alaa

Reputation: 85

How to validate dropdown list populated from SQL in asp.net (UnobtrusiveValidationMode) error

I have a drop down menu that is populated from SQL database and the default value is: (Select Developer). And I have a form wizard and the second step of the wizard is to select developer.
I want to validate this drop down menu; if the user keep it as it with the default value(Select Developer), the error msg should appear. I got this error:

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).

Following is my code:

.aspx:

    <asp:DropDownList ID="developers_DropDownList" name="developers_DropDownList" class="form-control col-md-7 col-xs-12" runat="server">
    </asp:DropDownList>
    <asp:RequiredFieldValidator ID="RequiredValidator1" runat="server" 
       ErrorMessage="Please select a value!"   
       ControlToValidate="developers_DropDownList" 
       InitialValue="Select Developer"></asp:RequiredFieldValidator>

.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindDevelopers();
        }
    }
protected void BindDevelopers()
    {
        SqlConnection con = new SqlConnection("Data Source=RC-8573\\SQLEXPRESS;Initial Catalog=DataManagment;Integrated Security=SSPI");
        con.Open();
        SqlCommand com = new SqlCommand("select * from Users WHERE role = 'Designer'", con);
        SqlDataAdapter da = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
        da.Fill(ds);  // fill dataset
        developers_DropDownList.DataTextField = ds.Tables[0].Columns["user_name"].ToString();
        developers_DropDownList.DataValueField = ds.Tables[0].Columns["user_id"].ToString();
        developers_DropDownList.DataSource = ds.Tables[0];
        developers_DropDownList.DataBind();
        developers_DropDownList.Items.Insert(0, new ListItem("Select Developer", "0"));
    }

web.debug.config and web.config:

    <configuration>
    <appSettings>
        <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2">
      <assemblies>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5.2"/>
    <customErrors mode="Off"/>
  </system.web>
</configuration>

Edit1:

@Tetsuya Yamamoto

1- First, I add the <appSettings> in web.config.

2- Second, I create file->new->file->global application class "global.asax" and put your code inside Application_Start.

3- Then I put in .aspx

<form .....>
<asp:ScriptManager runat="server" EnableScriptGlobalization="True" EnableCdn="True">
        <Scripts>
            <asp:ScriptReference Name="jquery" />
            <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" />
        </Scripts>
    </asp:ScriptManager>
<asp:DropDownList ID="developers_DropDownList" name="developers_DropDownList" class="form-control col-md-7 col-xs-12" runat="server"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredValidator1" runat="server" 
           ErrorMessage="Please select a value!"   
           ControlToValidate="developers_DropDownList" 
           InitialValue="Select Developer"></asp:RequiredFieldValidator> 

I got this error:

'jquery' is not a valid script name. The name must end in '.js'.

and also in global.asax, I got:

ScriptResourceDefenition does not contain a defenition for LoadSuccessExpression

Edit2:

After implementing all @Tetsuya Yamamoto notes, I did not got any error but, still there is no validation error appear when I leave the drop down list as it (Select Developer)!!!!!

Upvotes: 0

Views: 1101

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

First, ensure these lines already available in web.config (not only web.debug.config):

<appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Then, try adding ScriptManager.ScriptResourceMapping.AddDefinition method on Application_Start inside Global.asax:

protected void Application_Start(object sender, EventArgs e)
{
    string jqversion = "1.12.4"; // match this to available jQuery version you have
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
    {
        Path = "~/Scripts/jquery-" + jqversion + ".min.js",
        DebugPath = "~/Scripts/jquery-" + jqversion + ".js",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + jqversion + ".min.js",
        CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + jqversion + ".js",
        CdnSupportsSecureConnection = true,
        LoadSuccessExpression = "window.jQuery"
    });
}

The next important thing, place WebUIValidation.js after referencing jQuery in asp:ScriptReference element as this:

<asp:ScriptManager runat="server" EnableScriptGlobalization="True" EnableCdn="True">
    <Scripts>
        <asp:ScriptReference Name="jquery" />
        <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" />
    </Scripts>
</asp:ScriptManager>

To resolve second issue regarding invalid name, use Manage NuGet Packages menu to install both AspNet.ScriptManager.jQuery & AspNet.ScriptManager.jQuery.UI.Combined packages, or type those lines below in Package Manager Console (remember to set Copy Local as True afterwards):

Install-Package AspNet.ScriptManager.jQuery

Install-Package AspNet.ScriptManager.jQuery.UI.Combined

Remarks for ValidationSettings:UnobtrusiveValidationMode setting in MSDN documentation:

If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic. If this key value is set to "WebForms", ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.

Update Note:

The error regarding UnobtrusiveValidationMode and usage of LoadSuccessExpression method can only be encountered when project's targetFramework being set to .NET 4.5 or later (MSDN documentation), they may not exist when targetFramework being set to earlier version (4.0). If you want to run the project in version 4.0 mode, try to skip all steps above except installing packages and use this configuration instead:

<system.web>
    <compilation debug="false" targetFramework="4.0" />
    <httpRuntime targetFramework="4.0" />
</system.web>

Reference:

ASP.NET 4.5 ScriptManager Improvements in WebForms (MSDN Blog)

Similar issues:

ASP.Net 2012 Unobtrusive Validation with jQuery

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

'jquery' is not a valid script name. The name must end in '.js'

Upvotes: 2

Related Questions