ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Enterprise Application Development
    EC-332
    Progress0 / 37 topics
    Topics
    1. Overview of Enterprise Application Development: Microsoft technology history2. Introduction to .NET and its architecture3. Concept of MSIL, CLR, CLS, CTS4. Introduction to .NET framework: Managed and Unmanaged Code5. .Net Assembly6. Introduction to C# fundamentals7. Boxing and Unboxing8. Implementing multi-tier architecture9. Introduction to ADO.Net: SQL Injection, parameterized queries10. Usage of data set, Data adapter and command builder in disconnected model11. Introduction to delegate: Multicast delegates12. Introduction to windows forms13. HTML14. Introduction to javascript: javascript and its data types, variables, functions15. Debugging javascript using Firebug16. Introduction to various object models: Browser's Object (BOM), Document Object Model17. Introduction to Jquery: Jquery effects18. Introducing LINQ: LINQ to Objects, LINQ to SQL19. Query syntax, Operations (projection, filtering and join) using Linq Queries20. Introduction to ADO.NET entity framework: The entity data model, CSDL21. Eager vs lazy loading, POCO classes, DBContext API22. Querying entity data models23. Introduction to ASP.NET MVC24. MVC application structure, Controllers overview25. Action Methods, Parameterized action methods26. Introduction to razor syntax27. Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28. Data annotations, Client and Server Side Validation29. Validation and model binding, Validation and model state30. MVC Membership, Authorization and security31. Introduction to service-oriented architecture: SOAP, WSDL32. Service contract, Data contract, XML, WCF bindings33. ABC of WCF, Restful services34. Consuming rest services (CRUD operations) using Jquery AJAX and JSON35. Introduction to web API36. Example of web API using CRUD Example37. MVC routing
    EC-332›Validation and model binding, Validation and model state
    Enterprise Application DevelopmentTopic 29 of 37

    Validation and model binding, Validation and model state

    7 minread
    1,186words
    Intermediatelevel

    In ASP.NET Core, model binding and validation are key concepts that help manage user input and ensure that data conforms to expected rules. Let's dive into how these two concepts work together and how model state is involved in the process.

    1. Model Binding:

    Model binding is the process by which ASP.NET Core takes data from an HTTP request (such as form data, query strings, route data, etc.) and maps it to a model object in the controller. This allows you to work with strongly typed objects instead of handling raw request data like strings or integers.

    When a form is submitted, ASP.NET Core will automatically bind the incoming data to your model properties based on the names of the form fields and the model's property names.

    How Model Binding Works:

    1. The user submits a form.
    2. The data from the form is sent to the server (usually as a POST request).
    3. ASP.NET Core extracts the data from the request and uses the model binding process to populate the corresponding properties of the model object.
    4. The model is then passed to the action method in the controller.

    For example, if you have a model like this:

    public class UserModel
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    

    And your Razor view has a form like this:

    <form method="post">
        <label for="Name">Name:</label>
        <input type="text" name="Name" id="Name" />
        
        <label for="Age">Age:</label>
        <input type="number" name="Age" id="Age" />
        
        <button type="submit">Submit</button>
    </form>
    

    When the form is submitted, ASP.NET Core automatically binds the form data to the UserModel object based on the field names (Name and Age). This means the values entered by the user in the form are automatically placed in the corresponding properties of UserModel.

    Key Points about Model Binding:

    • It works with query parameters, form fields, and route data.
    • It automatically handles simple types (like strings, ints) and complex types (like models with other models or collections).
    • It can handle binding nested models as well (i.e., models with properties that are themselves models or lists of models).

    2. Validation:

    Validation is the process of ensuring that the data received in the model is correct and follows predefined rules (e.g., required fields, correct formats, acceptable ranges). In ASP.NET Core, validation is typically done using data annotations (attributes like [Required], [StringLength], etc.), or custom validation logic.

    Validation Flow:

    1. Apply Data Annotations: You apply data annotations to the properties of your model to define validation rules.
    2. Model Binding: When a request is made, the data binding process automatically populates the model with values from the request.
    3. Validation: Once the model is bound, the validation process is triggered. If any data annotations are violated (e.g., a required field is empty or a number is out of range), validation errors are generated.

    Example of a model with validation:

    public class UserModel
    {
        [Required(ErrorMessage = "Name is required")]
        [StringLength(50, MinimumLength = 2, ErrorMessage = "Name must be between 2 and 50 characters")]
        public string Name { get; set; }
        
        [Range(18, 100, ErrorMessage = "Age must be between 18 and 100")]
        public int Age { get; set; }
    }
    

    In the above model, Name is required and must be between 2 and 50 characters, while Age must be between 18 and 100.


    3. Model State:

    Model state is the collection of all validation information associated with a model. It includes whether the model passed validation or if there were errors (like required fields missing, invalid data, etc.).

    ASP.NET Core provides the ModelState object, which holds the validation state and errors. It is crucial for ensuring that only valid data is processed.

    Key Concepts of Model State:

    • ModelState.IsValid: A boolean property that returns true if the model passed all validation checks and false if there were any validation errors.
    • ModelState.Errors: A collection of error messages that correspond to validation failures for each property in the model.
    • ModelState.AddModelError: This method is used to add custom error messages manually to the model state.

    Example of Using ModelState:

    When you handle a form submission in a controller, ASP.NET Core automatically populates the ModelState with any validation errors that were triggered by data annotations.

    [HttpPost]
    public IActionResult Submit(UserModel model)
    {
        if (ModelState.IsValid)
        {
            // If the model is valid, proceed with saving the data
            // or other processing
            return RedirectToAction("Success");
        }
        else
        {
            // If the model is not valid, return the view with errors
            return View(model);
        }
    }
    

    In this example, if any validation rule is violated (like if Name is left empty or Age is out of the specified range), the ModelState.IsValid property will be false, and the controller action will return the view with the validation errors.

    How ModelState Works:

    • On Validation Failure: If a user submits a form with invalid data (e.g., leaving a required field empty), the model state will be invalid, and the form will not be processed.
    • Validation Errors: If validation fails, ModelState will contain a collection of error messages associated with the specific properties that failed validation.

    You can access these errors in your Razor views and display them next to the corresponding input fields:

    <form method="post">
        <label for="Name">Name:</label>
        <input type="text" name="Name" id="Name" />
        <span asp-validation-for="Name"></span>
        
        <label for="Age">Age:</label>
        <input type="number" name="Age" id="Age" />
        <span asp-validation-for="Age"></span>
        
        <button type="submit">Submit</button>
    </form>
    
    @* Display validation summary *@
    <div>
        <ul>
            @foreach (var error in ViewData.ModelState.Values.SelectMany(v => v.Errors))
            {
                <li>@error.ErrorMessage</li>
            }
        </ul>
    </div>
    

    Summary:

    1. Model Binding: The process that maps HTTP request data (from forms, query strings, or route data) to your model properties. ASP.NET Core automatically binds incoming data to your model.

    2. Validation: The process of checking whether the model data is valid according to rules defined via data annotations or custom logic. Validation is done after model binding but before any data is processed or stored.

    3. ModelState: Represents the validation status and errors related to the model. You can check ModelState.IsValid to determine if the model is valid and handle validation errors accordingly.

    • ModelState.IsValid: Checks if the model passed validation.
    • ModelState.AddModelError: Allows you to add custom errors to the model state.

    These concepts work together to ensure that data submitted by the user is correct and meets the required validation rules before it is processed or stored.

    Previous topic 28
    Data annotations, Client and Server Side Validation
    Next topic 30
    MVC Membership, Authorization and security

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,186
      Code examples0
      DifficultyIntermediate