Lesson 4 - Data processing and validations in ASP.NET Core MVC

C# .NET ASP.NET ASP.NET Core ASP.NET Core MVC Basics Data processing and validations in ASP.NET Core MVC

In the previous lesson, Form handling in ASP.NET Core MVC, we started with form handling and wiring the model to the view. We're gonna finish the simple calculator in today's C# .NET tutorial.

Submitting forms

When we submit our form, nothing happens yet. This is because the form sends data to the same page. The request is then captured by the Index() method in the controller, which looks like this:

public IActionResult Index()
{
    Calculator calculator = new Calculator();
    return View(calculator);
}

Even after submitting the form, a new calculator instance is created, which has a zero result and is set to the view. Therefore, our result is still zero. The situation of submitting a form to a page, which should process it, is sometimes called PostBack. We need to respond to this situation in a different way than rendering the page meant for the situation when the user hasn't sent anything yet.

We add another Index() method to the controller, this time with a parameter and the HttpPost attribute:

[HttpPost]
public IActionResult Index(Calculator calculator)
{
    if (ModelState.IsValid)
    {
        calculator.Calculate();
    }

    return View(calculator);
}

In the method, we get the calculator instance as a parameter as it was created from the values in the submitted form. If the model is valid, which we can find out using the ModelState class, we call the Compute() method. Finally, we return the view to which we pass the given model with the values ​​and the result.

The method is marked with the [HttpPost] attribute. By that we say that we wish it to be called only if the form has been submitted. ASP.NET always calls the overload method that best suits the situation. So the form submission won't fall into the first Index() method anymore, but into the new one.

We can try the application to see the result of the operation:

An ASP.NET MVC calculator

Other fields remain filled as well because the value is retrieved from the model that has it set from POST.

GET and POST

It would be good to say that besides the POST method, there's also a GET method. Both methods can be used to send data to our application.

We already know that we use the POST method to submit form values. Data is sent within the HTTP request to the server. Although it doesn't need to be strictly followed, the POST method is primarily used to submit new data.

Using the GET method, we pass data through the URL address. If we wanted to force it in a controller method, we could use the [HttpGet] attribute similarly as we did it with POST.

Let's create a simple example of using a parameter passed by the GET method. For example, if we wanted to specify a dedication in the URL for whom the calculator was created, the URL would look like this:

http://localhost:50913/?name=Charles

Or like this if we provided the full form:

http://localhost:50913/Home/Index?name=Charles

Your port will, of course, be different again. To read this value, we'll move to the first Index() method to which we'll add a parameter. We'll pass it to the view using ViewBag:

public IActionResult Index(string name)
{
    Calculator calculator = new Calculator();
    ViewBag.Name = name;
    return View(calculator);
}

We'll print the parameter in the view in the <h2> heading:

<h2>
        Calculator
        @if (ViewBag.Name != null)
        {
            <text> for @ViewBag.Name</text>
        }
</h2>

If the name GET parameter is set (not null), we write "for" and the content of this parameter to the heading. If we print text in the @if construct, it should be wrapped in the <text> element;

The result:

Calculator
https://local­host:44337/?na­me=Charles

We could just as well pass the parameter to the model instead to the view. I have no idea how to use it in our calculator, however, in the app with the random number generator, such URL parameter could indicate how many numbers we want to generate.

So we know how to pass data to the server script either through the URL using the GET method or through the body of the HTTP request using the POST method. POST is mainly used for forms. If we want the value to be entered as a link, we use GET.

Labels

Form field labels contain text with the name of the property they are bound to. Labels such as "Number1" aren't very nice for the user. Therefore, we'll add attributes with more descriptive names to the properties in the Calculator class:

public class Calculator
{
    [Display(Name = "1st number")]
    public double Number1 { get; set; }
    [Display(Name = "2nd number")]
    public double Number2 { get; set; }
    public double Result { get; set; }
    [Display(Name = "Operation")]
    public string Operation { get; set; }
    public List<SelectListItem> PossibleOperations { get; set; }

    // ...

We need to add using System.ComponentModel.DataAnnotations; to the attributes.

The result:

An ASP.NET MVC calculator

Validation

The last topic that we're gonna try on our calculator is validation. You must have already found out that if you don't enter a number or you manage to submit a string instead of a number, ASP.NET won't allow you to submit the form. Validations are generated automatically based on the data types of the given model property and are both client-side and server-side.

If you enter an invalid input, it'll be captured by a JavaScript validator before sending it to the server. Therefore, the request won't be sent at all. To make sure this works every time, the same validation must be on the server because the user can, for example, disable JavaScript.

We provide additional validation requirements as attributes. The [Required] attribute allows us to specify that the input field is required. All non-nullable value types (e.g. int, decimal, DateTime...) are considered as Required automatically.

For numbers, we can also validate their range, for example:

[Range(1, 100, ErrorMessage = "Enter the number from 1 to 100.")]

Note that using validation attributes, we can easily specify the message that is displayed to the user when the value is entered incorrectly.

For strings, we can validate their length, for example:

e.g. [StringLength(5)]

Or validate them using regular expressions:

[RegularExpression("\\d+", ErrorMessage = "Invalid code")]

You can try that the messages will really show up. For some fields (for example, for the numbers) these are created automatically by the framework using JavaScript, or the browser will customize it itself. Try to type letters in the field for the 1st number:

ASP.NET Core MVC validations

The calculator model is now full of attributes and is customized for the View. Such models are often called ViewModels. You should know this term if you've ever worked with WPF.

That would be all for our calculator. In the next lesson, Modifying the MVC template in ASP.NET Core, we'll start something more interesting. It'll be a personal blog with an administration. The source codes of today's project are available for download below.


 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Activities (2)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!