Currently, Microsoft have release its Core 1.1 and we are sure there will be more supports in Core and related libraries. Maybe there have been newer versions when you read my post.

In this post, we will discuss how to create a simple register form submission with Model and View data binding. To building this demo, this post from Ed Andersen gives me a lot help, if you have any question about data binding in .Net MVC, that blog will certainly help you.

First of all, I wish you own some basic knowledge about the .Net MVC and I will try to make a full record of my process to create the demo. To begin with, you should have installed the last version of VS 2017 into your machine. I understand it supports in Mac and Linux now and you can use code or sublime to build your apps, however, we will only cover it in Windows with VS in this article since VS can give you a easier head start to learn the Core.

1. Create a .Net Core Solution

This part would be no big difference between .Net or previous version of Visual Studio. Just need to choose the “Core Web Application“. Then click “ok”.

Next, we pick “Web Application“. After click the “ok”, VS will help you create the project in the solution.

2. Create the Controller and View

In here, we will create a new controller and the related view.

In the new project, find the folder “Controllers” in the Solution Explorer, right click it, click “Add => Controller”, you will have a choice window, choose “MVC Controller – Empty”.

Then, we name our new controller as TestController, in Core or MVC, the name of controller is followed by the “Controller”, just as our Test Controller named as “TestController”. This is the principle of Core and MVC.

After that, the VS will load and create the following cs file for you.

Next, we are going to create the page related to the controller. In Core, we can just create the view with the related name and Core is smart enough to link your view to the controller.

Here, just like the adding controller, right click the folder “Views” in the solution Explorer, click “Add => New Folder”, add a folder with name “Test”, it should be the same name as your controller (the reason is above). Then, Right click the Test folder, “Add => View”, create a View named as “Index”.

The reason why we put the name is “Index” is that : we need to match the name as the IActionREsult method in your controller. Since in our controller, we have the only IActionREsult method whose name is “Index”, since we are OK to use this controller method, we need to keep the name as “Index” in the view name. And the view name will be shown in the url, however, since it is index, it is blank in URL, rihgt?

Now, in order to test our new View, type into some test string as me.

Now, start your application, type into the your URL as localhost:xxxxx/test, it should show you this page.

3. Create View Model

I prefer to call this model as view model, this is linked to show in the page. For a project or solution, we need create some models for data or business layers, however, in here, this model is only used for web pages.

Maybe you may consider to use the data model or business model together with the view model. In my opinion, it may have more requirements from web pages and back end. For example, when you show some data to the user, you just need to show the product names only, instead of product ID together, therefore, you need to hide the certain part of your model which is not a good way to build your project, it will be too easy to leak risk information to your web page. And, for your web view model, we may need some validation definition in your class, which may not be not necessary for your business or data layer. You may notice it in the following example.

Create a Folder in your solution, and name it as “ViewModels”, then create a C# class “RegisterForm”, you may use the following code to create your class.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Threading.Tasks;

namespaceDataBinding.ViewModels

{

publicclassRegisterForm

{

publicRegisterForm()

{

GenderOptions=newList{"Male","Female"};

}

[StringLength(160,MinimumLength=6)]

[DataType(DataType.EmailAddress)]

[Required()]

[DisplayFormat]

publicstringEmail{get;set;}

[StringLength(20,MinimumLength=3)]

[Required()]

publicstringUserName{get;set;}

[StringLength(6,MinimumLength=4)]

[Required()]

publicstringGender{get;set;}

publicListGenderOptions{get;set;}

[DataType(DataType.Password)]

[StringLength(25,MinimumLength=6)]

[Required()]

publicstringPassword{get;set;}

[Compare("Password")]

[DataType(DataType.Password)]

[StringLength(25,MinimumLength=6)]

[Required()]

publicstringConfirmPassword{get;set;}

}

}

Please notice we added “using System.ComponentModel.DataAnnotations;” in the top, since we are using the annotation to check the user input from page. Some developers may prefer the JS validation for user input, but it may take the risk of code modified from front end. Since we are using the MVC, pages are related to certain models, the validation of whole view model may be a better way to deal with the user input data. As the input is validate from back end, it enjoys a higher level of security. Of course, if you can add front JS validation plus the back end annotation, it would be the greatest fit, since user can get the alert before submit the form. You can easily take the benefit of using some front end JS framework.

4. Add the Form Model to the View

Let’s go back to our view cshtml file. Add the following code to your file.

Now, start your application, you may get an error message.

If you look at our RegisterForm class, you may find that we don’t have any value for GenderOption until an constructor is called. Therefore, we need to construct one model instance then return that value to the view page.

We go to our controller file, modify to the following code.

1

2

3

4

5

6

7

8

9

10

11

using DataBinding.ViewModels;

namespaceDataBinding.Controllers

{

publicclassTestController:Controller

{

publicIActionResult Index()

{

returnView(newRegisterForm());

}

}

}

Here, we create an instance of RegisterForm and return to the view page.

Let’s go back to our error message and think more. Do we have another way to do it, since this gender value is hard-coded into the model class? Yes, we may create Enum for gender values instead of hard-coded in to the class. Before we return the RegisterForm instance, just need to set the GenderOptions to the value of our Enum to the instance. Anyway, both of them are better to hard-code the value in your html or JS side, that would be super easy to be modified… I wish you can understand MVC better with this error.

5. Modify our Controller to Handle Our Submit

Before modify our controller, let’s try click on the button to submit first. In this case, we leave all the input as blank.

Nothing happens. Open the “Chrom Inspect”, click the “Network” to monitor the web calls, you may notice after you click on the submit, it returns 200 ok, which means no error. But we already add DataAnnotations in our model, it should have a validation, rihgt?

The reason is the call never went to the right place, or, it has no place to go in our case here! In the view page, it returns the model with user input to the controller. However, in our controller, we only have one method IActionResult Index() , what we need is a Overload as IActionResult Index(RegisterForm form).

Let’s add these code into your controller.

1

2

3

4

5

6

7

8

9

10

11

12

[HttpPost]

[ValidateAntiForgeryToken]

publicIActionResult Index(RegisterForm register)

{

if(ModelState.IsValid)

{

// return to home page

returnRedirectToAction("Index","Home");

}

// return the current page with model and the validion result.

returnView(register);

}

Then let’s start our app, and submit a blank register, you would get this page with alerts.

If you fill in all the data, it would redirect you to the web home page. Done!

6. Retrospective

If you put a debug into your code at this line while submit a blank form, you may notice this debug value.

In the ModelState, you may find the details about all the validations in your page input.

With this detailed information, we may have more control with the data from user side and we may customize the handler based on the validation result.

You may like to made the alter color as red, just need to modify your global or local cshtml file, or css file.

One more thing I notice is that we don’t show the alter for Gender selection. Since this field is required, if not selected it should show something, however, there is no message in the page after the submit. I believe we need modify somewhere in the cshtml or in the model class. If you find it, please let me know.

We are a group of volunteers and opening a new scheme in our community.
Your web site offered us with valuable info to
work on. You have done a formidable job and our entire community will be grateful to you.

Pretty nice post. I just stumbled upon your
weblog and wished to say that I’ve really enjoyed surfing around your blog posts.
After all I will be subscribing to your feed and
I hope you write again soon!

Can I just say what a rerlief to find someone that rally understands
what they aree talking about over the internet.
You certainly realize how to bring an issue to light and make it important.
Morre people should look at this and understand this side of
thhe story. I can’t believe you aree not more
popular since you surely possess the gift.

Hmm is anyone else experiencing problems with the images on this blog loading?
I’m trying to determine if its a problem on my end or if
it’s the blog. Any feedback would be greatly appreciated. https://goo.gl/maps/RLPFGxUQTms

I am extremely impressed together with your writing talents
and also with the structure for your blog. Is that this a paid
subject or did you modify it yourself? Anyway keep up the excellent quality writing, it’s uncommon to see a great weblog like this one nowadays..

I have been exploring for a little bit for any high-quality articles
or weblog posts in this sort of area . Exploring in Yahoo I ultimately stumbled
upon this web site. Studying this info So i am happy to express that I have
an incredibly excellent uncanny feeling I found out just what I needed.

I most certainly will make sure to do not omit this site and give it a look regularly.

When buying gold, make certain that your
receipt is clearly marked with the karat weight, in addition to the producer.
These are things you want to know in case you later need to appraise or sell the piece, or maybe have it re-sized.

I see you don’t monetize your site, don’t waste your traffic,
you can earn extra bucks every month because you’ve got hi quality content.
If you want to know what is the best adsense alternative,
type in google: adsense alternative Mertiso’s tips