Wrox Programmer Forums
|
BOOK: Beginning ASP.NET Web Pages with WebMatrix
This is the forum to discuss the Wrox book Beginning ASP.NET Web Pages with WebMatrix by Mike Brind, Imar Spaanjaars ; ISBN: 978-1-1180-5048-4
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Beginning ASP.NET Web Pages with WebMatrix 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 January 26th, 2012, 11:49 AM
Authorized User
 
Join Date: Aug 2010
Posts: 50
Thanks: 7
Thanked 0 Times in 0 Posts
Default Chapter 11: Finishing the Classifieds Form

Hi,
/
I keep getting the following error. Do I need to remove the "$"

Server Error in '/' Application.
2 : $75.00 - Input string was not in a correct format.
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.FormatException: 2 : $75.00 - Input string was not in a correct format.

Source Error:

Line 55: sql = @"INSERT INTO Items (Title, Description, Price, CategoryId, DatePosted, Condition, Duration) VALUES (@0, @1, @2, @3,GetDate(),@4, @5)";
Line 56: var parameters = new[]{Request["title"], Request["description"], Request["price"], Request["categoryId"], Request["condition"],Request["duration"]};
Line 57: db.Execute(sql, parameters);
Line 58: Response.Redirect("~/Default.cshtml");
Line 59: result = "Your advertisement details have been sent to you by email";

\Sell.cshtml Line: 57

Code:

Code:
@{
    var db =Database.Open("Classifieds");
    var sql = "SELECT * FROM Categories";
    var categories = db.Query(sql);
    
    Page.Title="Post Your Advertisement";
    var result = "";
    if(IsPost){
        if(Request["title"].IsEmpty()){
            ModelState.AddError("title", "Please provide a title");
        }
        if(Request["title"].Length > 200){
            ModelState.AddError("title","Your title cannot exceed 200 characters");
        }
        if(Request["description"].IsEmpty()){
            ModelState.AddError("description", "You must provide a description");
        }
        if(Request["duration"].IsEmpty()){
            ModelState.AddError("duration", "Please choose a duration");
        }
        if(Request["price"].IsEmpty()){
            ModelState.AddError("price", "Please provide a price");
        }
        if(Request["price"].IsDecimal () && !Request["Price"].IsEmpty()){
            ModelState.AddError("price", "Please provide a valid number for the price");
        }
        if(Request["condition"].IsEmpty()){
            ModelState.AddError("condition", "Please state the condition of your item");
        }
        if(Request["email"].IsEmpty()){
            ModelState.AddError("email", "Please provide your email address");
        }
        if(!Request["email"].IsEmpty() && !Functions.IsValidEmail(Request["Email"])){
            ModelState.AddError("email", "Please provide a valid email address");
        }
        if(Request["categoryId"].IsEmpty()){
            ModelState.AddError("categoryId", "Please choose a category for your item");
        }
        if(!ModelState.IsValid){
            ModelState.AddFormError(@"Please fix the errors below before submitting the form");
        }else {
            var message ="<p>Details of your item for sale:</p>";
            message += "Title: " + Request["title"] + "<br />";
            message += "Description: " + Request["description"] + "<br />";
            message += "Duration: " + Request["duration"] +  "days<br />";
            message += "Price: " + String.Format(" {0:c}", Request["price"].AsFloat());
            message += "<br /> ";
            message += "Condition: " + Request["condition"];
            WebMail.Send(
                to: Request["email"],
                subject: "Advertisement Confirmation",
                body: message,
                isBodyHtml: true
                );
            sql = @"INSERT INTO Items (Title, Description, Price, CategoryId, DatePosted, Condition, Duration) VALUES (@0, @1, @2, @3,GetDate(),@4, @5)";
            var parameters = new[]{Request["title"], Request["description"], Request["price"], Request["categoryId"], Request["condition"],Request["duration"]};
            db.Execute(sql, parameters);
            Response.Redirect("~/Default.cshtml");
            result = "Your advertisement details have been sent to you by email";
        }
        
    }
}
<script type="text/javascript">
    $(document).ready(function(){
        $("#post-advert").validate({
            rules:{
                title:{
                    required: true,
                    maxlength: 200
                },
                 description: "required",
                 duration: "required",
                 condition: "required",
                 categoryId: "required",
                price:{
                    required: true,
                    number: true
                },
                email:{
                    required: true,
                    email: true,
                },
        },
        messages:{
            title:{
                required: "*You must provide a title",
                maxlength: "*Your title must not exceed 200 characters"
            },
            description: "*You must provide a description",
            duration: "*You must indicate a duration",
            condition: "*You must specify the condition of your item",
            categoryId: "You must choose a category for your item",
            price:{
                required: "*You must provide a price",
                number: "*Your price must be a valid number"
            },
            email:{
                required: "*You must provide your email address",
                email: "*You must provide a valid email address"
            },
        },
        errorPlacement: function(error, element){
            if(element.is(":radio")){
               error.prependTo($("#radio-error"));
            }
            else{
                error.insertAfter(element);
            }
        }
    });
});
</script>
<div>@result</div>
<form id=" ="post-advert" action="@Href("~/Sell")" method="post">
    <fieldset>
        <legend>Post Your Advertisement</legend>
        @Html.ValidationSummary(true)
        <div>
            <label for="title">Title</label>
        </div>
        <div>
            <input type="text" name="title" value="@Request["title"]" />
            @Html.ValidationMessage("title")
        </div>
        <div>
            <label for="description">Description</label>
        </div>
        <div>
            <textarea name="description">@Request["description"]</textarea>
            @Html.ValidationMessage("description")
        </div>
        <div>
            <label for="duration">Duration</label>
        </div>
        <div>
            <select name="duration">
                <option value="">--Choose One--</option>
                <option value="1" @Helpers.Selected("Duration","1")>1 Day</option>
                <option value="3" @Helpers.Selected("Duration","3")>3 Days</option>
                <option value="7" @Helpers.Selected("Duration","7")>7 Days</option>
                <option value="14" @Helpers.Selected("Duration","14")>14 Days</option>
            </select>
            @Html.ValidationMessage("duration")
        </div>
        <div>
            <label for="price">Price*</label>
        </div>
        <div>
            <input type="text" name="price" value="@Request["price"]" />
            @Html.ValidationMessage("price")
        </div>
        <div>
            <label for="categoryId">Category</label>
        </div>
        <div>
            <select name="categoryId">
                <option value="">--CHoose Category--</option>
                @foreach(var category in categories){
                    <option value="@category.CategoryId"
                        @(category.CategoryId == Request["categoryId"].AsInt() ? " selected=\"selected\"" : "")>
                        @category.Category</option>
                }
            </select>
            @Html.ValidationMessage("categoryId")
        </div>
        <div>
            <label for="condition">Condition</label>
        </div>
        <div>
            <input type="radio" name="condition" value="Fair" @Helpers.Checked("Condition","Fair") />Fair
            <input type="radio" name="condition" value="Good" @Helpers.Checked("Condition","Good") />Good
            <input type="radio" name="condition" value="As New" @Helpers.Checked("Condition","As New") />As New
            <span id="radio-error"></span>"
            @Html.ValidationMessage("condition")
        </div>
        <div>
            <label for="email">Your Email Address</label>
        </div>
        <div>
            <input type="text" name="email" value="@Request["email"]" />
            @Html.ValidationMessage("email")
        </div>
        <div>
            <input type="submit" name="submit" value="Post" />
        </div>
    </fieldset>
</form>
 
Old January 27th, 2012, 03:41 AM
Wrox Author
 
Join Date: Dec 2011
Posts: 57
Thanks: 1
Thanked 19 Times in 19 Posts
Default

The problem is in your validation logic. The following

Code:
if(Request["price"].IsDecimal () && !Request["Price"].IsEmpty()){
    ModelState.AddError("price", "Please provide a valid number for the price");
}
needs to be changed so that there is an exclamation mark before the IsDecimal test:

Code:
if(!Request["price"].IsDecimal () && !Request["Price"].IsEmpty()){
    ModelState.AddError("price", "Please provide a valid number for the price");
}
Then you will be unable to submit dollar signs with the number.
 
Old January 27th, 2012, 09:54 AM
Authorized User
 
Join Date: Aug 2010
Posts: 50
Thanks: 7
Thanked 0 Times in 0 Posts
Default

This is a little confusing, (!) when are we suppose to use it and when do we not use?

Thanks.
 
Old January 27th, 2012, 01:10 PM
Wrox Author
 
Join Date: Dec 2011
Posts: 57
Thanks: 1
Thanked 19 Times in 19 Posts
Default

The ! is the logical NOT operator. You use it on its own to test booleans. The IsDecimal() method returns true if the value being tested can be converted to a decimal, and false if not. There are two ways to test if the method will return false: use the NOT operator to see if the result of the test is not true; or simply test for false:

Code:
if(!value.IsDecimal())
or

Code:
if(value.IsDecimal() == false)
There is also actually a third which is effectively the same as the first:

Code:
if(value.IsDecimal() != true)
The first is the one that you will see most widely used because of its terseness.

Last edited by Mike Brind; January 27th, 2012 at 01:13 PM..





Similar Threads
Thread Thread Starter Forum Replies Last Post
on finishing this book jmahdi BOOK: Beginning ASP.NET 4 : in C# and VB 2 April 30th, 2011 03:50 PM
chapter 11 figure 11-7 relative positioning pelopito BOOK: Beginning CSS: Cascading Style Sheets for Web Design ISBN: 978-0-7645-7642-3 2 November 29th, 2007 06:11 AM
formatting a classifieds section. Part 2 afrika_people Classic ASP Databases 1 August 13th, 2004 04:40 PM





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