Razor Form – Create, Validate and Get User Input

In this chapter you will learn

  1. How to create Form in Razor?
  2. How to validate user Input
  3. How to Get User Input
  4. Restore Value after Page Refresh or PostBack

How to create Form in Razor?

There is no special rule for creating form. As you know Razor works with Pure HTML so you can design you Form in Pure HTML as follow.

Step 1 : Create a New Page and save it as Form.cshtml.
Step 2 : Create HTML Form






  • Let’s Understand It.

    This is Text Box has 3 properties.
    type="text" – It declares that it is a TextBox.
    name="txtBook" – It declares its identification name.
    value="@Request.Form["txtBook"]" – It restores Text Box value after Page Refresh or Post Back.
    @Html.ValidationMessage("txtBook") – It displays error messages which is defined in Razor Syntax for TextBook.


    How to Validate User Input

    You can validate User Input as follow

    Let’s Understand It.

    This method check textBook for empty. If textBook TextBox is empty it flash error message “Book Name is Required.”

    This method checks txtAuthor TextBox for string length. 40 is maximum length and 5 is minimum length. It means this box must be filled between 5 to 40 characters long. If condition fails then it will flash error message , “Author Name must be Minimum 5 chars long”

    This block gets executed only, if all the conditions match and validation process don’t return error messages.

    How to Get User Input

    You can get user input using Request.Form["Control Name"]. for example,

    Let’s Understand It.

    string variable BookName holds the textBook value.

    Restore Value after Page Refresh or PostBack

    You can restore control value after PostBack or after Page Refresh using @Request.Form[“txtBook”] method in value attribute. Example

    Let’s Put all together

    Output

    If Submitted Value is Empty

    Book Name :
    Book Name is Required.

    Author Name :
    AuthorName is Required.

    Submitted With Value

    You Entered:
    Book Name : C#-Rajor
    Author Name : Simon D.

    Book Name :

    Author Name :

    Summary

    In this chapter you learned how to create, validate, get user input and restore form data after post back. In the next chapter you will learn to store form data in database.


    Leave a Reply

    Your email address will not be published. Required fields are marked *