Asp.Net Core MVC Model Binding and Validation
|
Thursday, May 30, 2019
Model Validation Example in Asp.Net Core
In the previous post we
saw on how to perform form field validations using Model State, in this post we will see an example of using Model
Validations in a MVC Form. Following is the Model class with the validations.
Monday, May 27, 2019
Model Validation in Asp.Net Core
Validation is an important part of any application which accepts
inputs from users, the data entered by the user needs to be validated for
integrity before it is saved in the database. Validations could be on the type
of data like int, string, decimal etc. On the format of the data like email,
SSN, Phone Number etc. Also we might need custom validation specific to the
application.
Asp.Net Core MVC Model validation provides us an easy and effective way to validate user input, using Model validation we can specify the validation parameters in the Model object and the framework will take care of validating the inputs in the View.
Asp.Net Core MVC Model validation provides us an easy and effective way to validate user input, using Model validation we can specify the validation parameters in the Model object and the framework will take care of validating the inputs in the View.
Model Binding in ASP.NET Core
Model Binding is the process by which the incoming parameters from
a HTTP request are mapped to the parameters of the corresponding Action
Methods. The parameters can be route parameters or parameters of the Action
methods. Asp.Net core framework
takes care of matching the parameters from the request with the route/action
method parameters and populated the parameters automatically.
The Framework matched the HTTP parameters with the route/action method parameters using the parameter names, when a parameter name matches it populates the property value from the request and proceeds to match the next parameter.
The Framework matched the HTTP parameters with the route/action method parameters using the parameter names, when a parameter name matches it populates the property value from the request and proceeds to match the next parameter.
Sunday, May 26, 2019
Attribute routing in Asp.Net Core MVC
In the previous post we
saw about Routing in Asp.Net Core MVC Applications, and how
to define Routing in the Applications Startup, this is called conventional
routing. Asp.Net Core MVC applications also provide us another way to define
routes called Attribute Routing.
Attribute Routing
As the name suggests Attribute Routing is defined by defining routes in action methods using a Route attribute as follows.
Attribute Routing
As the name suggests Attribute Routing is defined by defining routes in action methods using a Route attribute as follows.
Defining multiple routes in Asp.Net Core MVC
In the previous post we
saw about Routing in Asp.Net Core MVC Applications, also we
saw different ways of defining simple routing. However for more complex
application this simple routing might not be enough, we might have to define
different routing paths for each module in the application like
/Accounts/. . .
/Contacts/. . .
/Reports/. . .
/Accounts/. . .
/Contacts/. . .
/Reports/. . .
In this post we shall
see on how to define multiple routing paths in Asp.Net Core MVC.
Remember we defined a simple routing which by default was pointing to Home/Index, let us extend this by adding 2 more paths to this routing pointing to the Employee & Users controller, the route definition will be as follows.
Remember we defined a simple routing which by default was pointing to Home/Index, let us extend this by adding 2 more paths to this routing pointing to the Employee & Users controller, the route definition will be as follows.
What is Asp.Net Core MVC Routing
In traditional Asp.Net Web Forms we access a page
using the pages URL like
http://localhost/index.aspx
But in Asp.Net MVC we don’t specify the page name or extension in the URL, instead we specify the Controllers action method in the URL and the controller takes care of rendering the corresponding view. Asp.Net Core MVC uses a routing Middleware to map the incoming request to the action method. Routes can be specified either in the startup or as attributes in the Controller / Action methods.
But in Asp.Net MVC we don’t specify the page name or extension in the URL, instead we specify the Controllers action method in the URL and the controller takes care of rendering the corresponding view. Asp.Net Core MVC uses a routing Middleware to map the incoming request to the action method. Routes can be specified either in the startup or as attributes in the Controller / Action methods.
Saturday, May 25, 2019
Wednesday, May 22, 2019
Injecting Service into Asp.Net Core View
In the previous posts we
saw on how register a service Dependency
Injection in the startup and inject the service to the MVC controller or Action
method. In some cases we might need to inject a service directly into the
View. A typical example is populating dropdown lists in the view.
If a view has dropdowns we cannot use the original Entity model since it will not contain the option values for the dropdown lists, in these cases we will create a custom View Model with will contain the properties from the entity model and additional lists to populate the dropdowns in the view. By injecting services to the view directly we can avoid this by injecting services directly to the view to populate the dropdown option values and continue using the entity model to display the model properties.
To inject a service directly to a view we need to use the @Inject directive. The syntax for the @Inject directive is as follows.
If a view has dropdowns we cannot use the original Entity model since it will not contain the option values for the dropdown lists, in these cases we will create a custom View Model with will contain the properties from the entity model and additional lists to populate the dropdowns in the view. By injecting services to the view directly we can avoid this by injecting services directly to the view to populate the dropdown option values and continue using the entity model to display the model properties.
To inject a service directly to a view we need to use the @Inject directive. The syntax for the @Inject directive is as follows.
Injecting Service into Asp.Net Core Action Methods
In the previous post we
saw on how to inject a service to the MVC
controller. This might not be needed always, there are cases where we will
need the service only for one action method in the controller. In this post we
shall see on how to inject a service to one of the action methods in a
controller.
The service and the service registration in the startup remains the same, instead of injecting the service in the controller’s constructor. When injecting the service in the action method we need to use the [FromServices] attribute. We will inject the service in the action method as follows.
The service and the service registration in the startup remains the same, instead of injecting the service in the controller’s constructor. When injecting the service in the action method we need to use the [FromServices] attribute. We will inject the service in the action method as follows.
Injecting Service into Asp.Net Core Controllers
In the previous example
we created an interface IUserService
and a service class UserService. We
also registered the service in the Asp.Net Core startup. In this post we will
see on how to inject this service in the constructor of MVC controller and use it to populate the view. To start with let
us create a new MVC controller and name it UserServiceController.
In the constructor of the Controller class we will pass a reference to the IUserService. Since we registered this interface with the service class in the startup, the Asp.Net runtime will inject an instance of the UserService class to the controller. Following is the code for the MVC controller.
In the constructor of the Controller class we will pass a reference to the IUserService. Since we registered this interface with the service class in the startup, the Asp.Net runtime will inject an instance of the UserService class to the controller. Following is the code for the MVC controller.
Sunday, May 19, 2019
Registering Service using Asp.Net Core Dependency Injection
Asp.Net Core provides built in support for Dependency Injection, we can register classes in the Application
startup and inject instances of these classes wherever required like
controller, views or other classes.
ASP.NET Core provides a built-in service container IServiceProvider to register class dependency. Services are registered in the Startup using the ConfigureServices method.
In previous examples we used to connect to the Database directly from the Controller layer, however in larger applications it is recommended to use a Service / Repository layer to interact with the database. Let us create a simple service class which will do the database operations, we will register this service in the Startup and inject this service in the controller using Asp.Net Core Dependency Injection.
ASP.NET Core provides a built-in service container IServiceProvider to register class dependency. Services are registered in the Startup using the ConfigureServices method.
In previous examples we used to connect to the Database directly from the Controller layer, however in larger applications it is recommended to use a Service / Repository layer to interact with the database. Let us create a simple service class which will do the database operations, we will register this service in the Startup and inject this service in the controller using Asp.Net Core Dependency Injection.
Dependency Injection in Asp.Net Core
Dependency Injection is a design pattern which helps eliminate
dependency between various classes and modules in a larger application.
Dependency Injection aims in creating dependent objects for a class outside the
class and injecting them dynamically into the class, instead of instantiating
the dependent classes inside the main class. By doing this Dependency Injection helps us develop Applications with better
modularity and test-ability.
Asp.Net Core provides built in dependency injection support for applications, in previous versions of Asp.Net dependency injection was implemented using 3rd party libraries like StructureMap, Unity etc. ASP.NET Core provides a built-in service container, IServiceProvider. Services are registered in the app's Startup.ConfigureServices method.
In Asp.Net Core a dependent service is registered with the service container in the ConfigureServices method of the Startup class as follows.
Asp.Net Core provides built in dependency injection support for applications, in previous versions of Asp.Net dependency injection was implemented using 3rd party libraries like StructureMap, Unity etc. ASP.NET Core provides a built-in service container, IServiceProvider. Services are registered in the app's Startup.ConfigureServices method.
In Asp.Net Core a dependent service is registered with the service container in the ConfigureServices method of the Startup class as follows.
Saturday, May 18, 2019
ViewModel, Partial Views and Layouts in Asp.Net Core
ViewModel, Partial Views and Layouts in Asp.Net Core
|
Entity Framework Core with Asp.Net MVC Core Getting Started
Layout in Asp.Net Core MVC Views
Every page on a website
will have some common elements like Header, Logo, Menu, Navigation links etc. A
layout helps to create a common view
for these re-usable part of the page and use it in each page of the
application.
A layout is also a view with .cshtml extension. The layout view defines the header, content area and the footer sections. In general re-usable content is placed in the header and footer sections, the content section varying content of the pages. The content section contains a statement @RenderBody(), which embeds the varying content of each page in the content section.
A typical layout view page looks like this.
A layout is also a view with .cshtml extension. The layout view defines the header, content area and the footer sections. In general re-usable content is placed in the header and footer sections, the content section varying content of the pages. The content section contains a statement @RenderBody(), which embeds the varying content of each page in the content section.
A typical layout view page looks like this.
Partial view with Model example in Asp.Net Core
In the previous post we
saw a simple Partial View example,
where a string from the partial view is displayed in the main view page. In
this post we will improve this example to take a Model object and display the
properties in the Model object.
When invoking a partial view from a main view, we can also pass a Model object to the partial view as follows. The properties in the passed model can be used in the HTML markup of the partial view.
When invoking a partial view from a main view, we can also pass a Model object to the partial view as follows. The properties in the passed model can be used in the HTML markup of the partial view.
Partial view example in Asp.Net Core
Partial views are views whose content gets embedded in other View
pages, partial views are added to other views using the <partial> element or using @Html.Partial helper tags. In this post we shall see a simple
example of how to create a partial view and embed it in the main view page.
Partial views are usually named with a _ character in from of the view name to differentiate between partial views and other views. The following line shows how a partial view is referenced inside other views.
Partial views are usually named with a _ character in from of the view name to differentiate between partial views and other views. The following line shows how a partial view is referenced inside other views.
Partial views in Asp.Net Core MVC Views
A Partial View is another view page with
.cshtml extension, Partial Views are
used to modularize larger view pages and also to re-use common functionality
across different views in the application.
Partial views improve maintainability by breaking down a large view page into modular views and embedding the partial views in the main view template. By doing this the markup code in the main view page reduces there by improving readability and maintainability.
Partial views also help reduce duplication of code in larger applications, if we have a common functionality / display content which is to be repeated in many places the a large application, then we can place the repeating content in a partial view and just embed the partial view wherever required. This reduces duplication of same logic in many places. Also improves maintainability since any change to the common logic needs to be done in only one place, in the partial view.
The syntax for including partial views varies by the version of Asp.Net Core used, in Asp.Net Core 2.1 we use the partial tag to include partial views as follows.
Partial views improve maintainability by breaking down a large view page into modular views and embedding the partial views in the main view template. By doing this the markup code in the main view page reduces there by improving readability and maintainability.
Partial views also help reduce duplication of code in larger applications, if we have a common functionality / display content which is to be repeated in many places the a large application, then we can place the repeating content in a partial view and just embed the partial view wherever required. This reduces duplication of same logic in many places. Also improves maintainability since any change to the common logic needs to be done in only one place, in the partial view.
The syntax for including partial views varies by the version of Asp.Net Core used, in Asp.Net Core 2.1 we use the partial tag to include partial views as follows.
Thursday, May 16, 2019
Displaying Bootstrap Model in an MVC View
In the previous posts we
saw on how to create Asp.Net Core MVC
Controllers and Views for CRUD operations. In this post let us add a little bit
of styling. Let us create a
bootstrap Model and display it on the click of a Bootstrap button.
We will add a bootstrap button and set its target to a Bootstrap model, below is the bootstrap button.
We will add a bootstrap button and set its target to a Bootstrap model, below is the bootstrap button.
Creating a ViewModel object and bind it to the View
In the previous post we
created a custom controller and we developed our own view and it worked. There
is one think to note in that sample, the controller was passing a list of
Employee object will all the properties, but the view was displaying only
specific properties. Though this works it’s not efficient while displaying
larger lists, we end up fetching way too much data from the database but not
using it. To avoid this we have to create a custom ViewModel object with only properties used in the view. In this
sample we will modify the previous example to use a ViewModel object.
First create another folder inside the Models folder, name it ViewModel we will create all our ViewModel objects inside this folder. Next create a class EmployeeSummary.cs in this folder as follows.
First create another folder inside the Models folder, name it ViewModel we will create all our ViewModel objects inside this folder. Next create a class EmployeeSummary.cs in this folder as follows.
Sunday, May 12, 2019
Asp.Net Core MVC - Creating an Empty Controller and develop Manually
In the previous sample
we saw on how to create a controller in Asp.Net
core MVC using the using Template to create all Action Methods for CRUD
operation, this was very easy since Visual Studio created us all the Action
Methods by default. This is very handy when we want to do CRUD operations,
however in some cases this might not come in very handy, we might want to
create our own action methods, in such cases we will create an Empty controller
without Action methods. In this post we shall see on how to create an Empty controller and build on top of
it.
Open Visual Studio, create a simple MVC project as we saw in our previous posts. Once the project is up and running we will add our empty controller. Follow the below steps to create an empty controller.
Open Visual Studio, create a simple MVC project as we saw in our previous posts. Once the project is up and running we will add our empty controller. Follow the below steps to create an empty controller.
Customize Validation error message in ASP.NET Core MVC
In the previous post we
saw on how to implement field level validations by adding validation attributes
to the Model class. We saw that the validation messages were auto generated
based on the validation rules, we might want to add custom validation messages,
we can do this by adding an ErrorMessage
property to the validation attributes.
In the sample below we will add custom error messages using the ErrorMessage property and see how this is reflected in the View.
In the sample below we will add custom error messages using the ErrorMessage property and see how this is reflected in the View.
Adding Model Validations in ASP.NET Core MVC Views
In the previous posts we
saw on how to create an Asp.Net Core MVC
controller and views to View, Edit and Delete detail using Entity Framework Core. In this post we will see on how to add Model
validations which will be applied to the Views to validate data before we
Add/Delete details to the database.
Asp.Net Core makes it easy to validate entities, all we need to do is to add the validation properties to the Model class and Asp.Net Core takes care of applying the validations in the view automatically. In the previous version of Asp.Net MVC we had to validate the user input fields in the View layer using Validation controls like Required Field validator, Range Validator, Regular expression validator etc, but Asp.Net Core takes care of this for us.
Asp.Net Core makes it easy to validate entities, all we need to do is to add the validation properties to the Model class and Asp.Net Core takes care of applying the validations in the view automatically. In the previous version of Asp.Net MVC we had to validate the user input fields in the View layer using Validation controls like Required Field validator, Range Validator, Regular expression validator etc, but Asp.Net Core takes care of this for us.
Subscribe to:
Posts (Atom)