locked
validation code RRS feed

  • Question

  • User955208585 posted

    I have aspx code below.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="XEx18ProductReceipt.Default" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Ch18: Product Receipt</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/site.css" rel="stylesheet" />
    <script src="Scripts/jquery-1.9.1.min.js"></script>
    <script src="Scripts/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
    <header class="jumbotron"><%-- image set in site.css --%></header>
    <main>
    <form id="form1" runat="server" class="form-horizontal">

    <div class="form-group">
    <label class="col-sm-3">Please select a category</label>
    <div class="col-sm-4">
    <asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="true"
    CssClass="form-control" DataTextField="LongName"
    SelectMethod="ddlCategory_GetData"
    ItemType="XEx18ProductReceipt.Category">
    </asp:DropDownList>
    </div>
    </div>

    <div class="row">
    <div class="col-xs-12">
    <asp:GridView ID="grdProducts" runat="server" AllowPaging="True"
    AutoGenerateColumns="False" DataKeyNames="ProductID"
    CssClass="table table-bordered table-condensed"
    ItemType="XEx18ProductReceipt.Product"
    SelectMethod="grdProducts_GetData" >
    <Columns>
    <asp:BoundField DataField="ProductID" HeaderText="ID"
    ReadOnly="True">
    <HeaderStyle CssClass="col-sm-2" />
    </asp:BoundField>
    <asp:BoundField DataField="Name" HeaderText="Name"
    ReadOnly="True">
    <HeaderStyle CssClass="col-sm-6" />
    </asp:BoundField>
    <asp:BoundField DataField="CategoryID" HeaderText="Category"
    ReadOnly="True">
    <HeaderStyle CssClass="col-sm-6" />
    </asp:BoundField>
    <asp:BoundField DataField="OnHand" HeaderText="OnHand">
    <HeaderStyle CssClass="col-sm-2 text-right" />
    <ItemStyle CssClass="text-right"></ItemStyle>
    </asp:BoundField>
    <asp:CommandField ShowEditButton="True" />
    </Columns>
    <HeaderStyle CssClass="bg-halloween" />
    <AlternatingRowStyle CssClass="altRow" />
    <EditRowStyle CssClass="warning" />
    </asp:GridView>
    <asp:EntityDataSource ID="EntityDataSource1" runat="server">
    </asp:EntityDataSource>
    </div>
    </div>

    <div class="row">
    <div class="col-xs-12">
    <p><asp:Label ID="lblError" runat="server"
    CssClass="text-danger" EnableViewState="false"></asp:Label></p>
    <asp:ValidationSummary ID="ValidationSummary1" runat="server"
    HeaderText="Please correct the following errors:" CssClass="text-danger" ShowModelStateErrors="true"/>
    </div>
    </div>
    </form>
    </main>
    </div>
    </body>
    </html>

    I need to show error messege when user  enter the invalid data for update the column like below.

    Data value should be 1 to 500 . and it should not be string. 

    Monday, April 16, 2018 11:10 AM

Answers

  • User-1838255255 posted

    Hi ndhakal,

    According to your description and code, i make a sample in my side, please check: 

    page.aspx:
                <asp:GridView Id="gridview1" runat="server" AutoGenerateColumns="False"  DataKeyNames="Id" ItemType="WebForm0418.Models.Product" UpdateMethod="gridview1_UpdateItem" SelectMethod="gridview1_GetData">
                    <Columns>
                        <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
                        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                        <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />
                        <asp:CommandField ShowEditButton="True" />
                    </Columns>
                </asp:GridView>
                <asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=DataStoreEntities" DefaultContainerName="DataStoreEntities" EnableDelete="True" EnableFlattening="False" EnableInsert="True" EnableUpdate="True" EntitySetName="Products" >
                </asp:EntityDataSource>
                <p><asp:Label ID="lblError" runat="server" 
    CssClass="text-danger" EnableViewState="false"></asp:Label></p>
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
    HeaderText="Please correct the following errors:" CssClass="text-danger" ShowModelStateErrors="true"/>
    
    Code behind: 
    DataStoreEntities storeEntities = new DataStoreEntities(); public void gridview1_UpdateItem(int id) { var product = storeEntities.Products.Find(id); if (product == null) { ModelState.AddModelError("", String.Format("Item with id {0} was not found", id)); return; } TryUpdateModel(product); if (ModelState.IsValid) { storeEntities.SaveChanges(); } } public IQueryable<WebForm0418.Models.Product> gridview1_GetData() { return storeEntities.Products; }
    Table Design: CREATE TABLE [dbo].[Product] ( [Id] INT IDENTITY (1, 1) NOT NULL, [Name] NVARCHAR (50) NOT NULL, [Price] INT NOT NULL, PRIMARY KEY CLUSTERED ([Id] ASC) );

    Result:

    Best Regards,

    Eric Du 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 18, 2018 7:54 AM

All replies

  • User-1838255255 posted

    Hi ndhakal,

    According to your description and code, i make a sample in my side, please check: 

    page.aspx:
                <asp:GridView Id="gridview1" runat="server" AutoGenerateColumns="False"  DataKeyNames="Id" ItemType="WebForm0418.Models.Product" UpdateMethod="gridview1_UpdateItem" SelectMethod="gridview1_GetData">
                    <Columns>
                        <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
                        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                        <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />
                        <asp:CommandField ShowEditButton="True" />
                    </Columns>
                </asp:GridView>
                <asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=DataStoreEntities" DefaultContainerName="DataStoreEntities" EnableDelete="True" EnableFlattening="False" EnableInsert="True" EnableUpdate="True" EntitySetName="Products" >
                </asp:EntityDataSource>
                <p><asp:Label ID="lblError" runat="server" 
    CssClass="text-danger" EnableViewState="false"></asp:Label></p>
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
    HeaderText="Please correct the following errors:" CssClass="text-danger" ShowModelStateErrors="true"/>
    
    Code behind: 
    DataStoreEntities storeEntities = new DataStoreEntities(); public void gridview1_UpdateItem(int id) { var product = storeEntities.Products.Find(id); if (product == null) { ModelState.AddModelError("", String.Format("Item with id {0} was not found", id)); return; } TryUpdateModel(product); if (ModelState.IsValid) { storeEntities.SaveChanges(); } } public IQueryable<WebForm0418.Models.Product> gridview1_GetData() { return storeEntities.Products; }
    Table Design: CREATE TABLE [dbo].[Product] ( [Id] INT IDENTITY (1, 1) NOT NULL, [Name] NVARCHAR (50) NOT NULL, [Price] INT NOT NULL, PRIMARY KEY CLUSTERED ([Id] ASC) );

    Result:

    Best Regards,

    Eric Du 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 18, 2018 7:54 AM
  • User955208585 posted

    I got another problem . My aspx.cs code is below. while i try to run this code, I always got error messege like below

    my aspx.cs code

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace XEx18ProductReceipt
    {


    using System.Web.ModelBinding;


    public partial class Default : System.Web.UI.Page
    {
    HalloweenEntities db = new HalloweenEntities();
    protected void grdProducts_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
    if (e.Exception != null)
    {
    lblError.Text =
    "A database error has occurred. " +
    "Message: " + e.Exception.Message;
    e.ExceptionHandled = true;
    e.KeepInEditMode = true;
    }
    else if (e.AffectedRows == 0)
    {
    lblError.Text =
    "Another user may have updated that category. " +
    "Please try again.";
    }

    }

    protected void grdProducts_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    public IQueryable<Category> ddlCategory_GetData()
    {
    return from c in db.Categories
    orderby c.LongName
    select c;
    }

    public IQueryable<Product> grdProducts_GetData(
    [Control] string ddlCategory)
    {
    // get first category ID from database
    // if nothing is passed in
    if (ddlCategory == null)
    ddlCategory = (from c in db.Categories
    orderby c.LongName
    select c).FirstOrDefault().CategoryID;
    // get the products for the selected category
    return from p in db.Products
    where p.CategoryID == ddlCategory
    orderby p.Name
    select p;
    }

    protected void grdProducts_PreRender(object sender, EventArgs e)
    {
    // to format the generated Bootstrap table
    grdProducts.HeaderRow.TableSection =
    TableRowSection.TableHeader;
    }

    }
    }

    Error 

    Server Error in '/' Application.


    Updating is not supported unless the UpdateMethod is specified.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NotSupportedException: Updating is not supported unless the UpdateMethod is specified.

    Source Error:

    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.


    Stack Trace:

    [NotSupportedException: Updating is not supported unless the UpdateMethod is specified.]
       System.Web.UI.WebControls.ModelDataSourceView.EvaluateUpdateMethodParameters(IDictionary keys, IDictionary values, IDictionary oldValues, ModelDataSourceMethod method) +2496813
       System.Web.UI.WebControls.ModelDataSourceView.EvaluateUpdateMethodParameters(IDictionary keys, IDictionary values, IDictionary oldValues) +19
       System.Web.UI.WebControls.ModelDataSourceView.GetUpdateMethodResult(IDictionary keys, IDictionary values, IDictionary oldValues, ModelDataSourceMethod method, Boolean isAsyncMethod, Nullable`1 cancellationToken) +49
       System.Web.UI.WebControls.ModelDataSourceView.GetUpdateMethodResult(IDictionary keys, IDictionary values, IDictionary oldValues) +47
       System.Web.UI.WebControls.ModelDataSourceView.ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) +23
       System.Web.UI.DataSourceView.Update(IDictionary keys, IDictionary values, IDictionary oldValues, DataSourceViewOperationCallback callback) +106
       System.Web.UI.WebControls.ModelDataSourceView.Update(IDictionary keys, IDictionary values, IDictionary oldValues, DataSourceViewOperationCallback callback) +168
       System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int32 rowIndex, Boolean causesValidation) +1210
       System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +877
       System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source, EventArgs e) +89
       System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
       System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e) +90
       System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
       System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +121
       System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +161
       System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
       System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
       System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +9758870
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639
    

     


    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2633.0

    Thursday, April 19, 2018 10:42 AM
  • User-1838255255 posted

    Hi ndhakal.

    Sorry for the late response. Have you solved the problem?

    I think you may lost to specify the UpdateMethod event for GridView. Like this.

    Aspx.
    <asp:GridView Id="gridview1" runat="server" AutoGenerateColumns="False"  DataKeyNames="Id" ItemType="WebForm0418.Models.Product"
                    UpdateMethod="gridview1_UpdateItem" SelectMethod="gridview1_GetData">
    
    Codebehind.
           DataStoreEntities storeEntities = new DataStoreEntities();
            public void gridview1_UpdateItem(int id)
            {
                var product = storeEntities.Products.Find(id);
                if (product == null)
                {
                    ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                    return;
                }
                TryUpdateModel(product);
                if (ModelState.IsValid)
                {
                    storeEntities.SaveChanges();
    
                }
            }
    

    If you still have any question, look forward to your reply.

    Best Regards,

    Eric Du

    Thursday, April 26, 2018 9:12 AM