Learn ASP.
NET Core Online
[Link] Core is a cross-platform, open-source framework for
building cloud-based web applications. [Link] Core Framework
becoming more popular among developers for various reasons
If you are familiar with earlier version of [Link] Code behind or
[Link] MVC you may find [Link] Core little easy, if not, nothing to
worry, Let’s learn [Link] Core step by step
What's new in [Link] Core?
Cross-platform & Container
Now we can create [Link] applications & deploy them to
Linux, macOS and Windows. Microsoft community have put
a huge effort into making Linux a first-class citizen for
running [Link].
[Link] Core allows developers to utilize all of new
(containers) technologies like Docker , Kuberenetes
Unified MVC & Web API frameworks
Multiple environments and development mode
Dependency Injection
WebSockets & SignalR
Asynchronous via async/await
Ths is one of the reasons why [Link] Core is faster is its
extensive use of asynchronous patterns within the new
MVC Framework and Kestrel frameworks.
Cross-Site Request Forgery (CSRF) Protection
High performance
Here are few important features of [Link] Core you must know.
[Link] Core Pre-requisites
Prior knowledge of HTML and C# is mandatory.
Understanding of [Link] WebForms or [Link] Mvc will
help to understand [Link] Core better (but not
mandatory)
Should have some working knowledge of LINQ, Entity
Framework and SQL Server for database related
operations.
Download [Link] Core IDE
To start with [Link] Core, First download the IDE, in google just
type "visual studio community", there you get free version of visual
studio to downlaod and practice
Learn [Link] Core with C# Examples
In this [Link] Core Tutorial you will learn different controls of
[Link] core, and how to develop web application using [Link] core
framework with many real-time examples, also some best practices
that software development companies ask during [Link] core
interview
.Net Core Introduction
Sample Project
[Link]
.Net Core [Link]
.Net Core WwwRoot
[Link] Core Middleware
Kestrel web server
.Net Core [Link]
[Link] Core Pages
Partial Pages Razor
Razor Page Methods
Form in Razor Pages
[Link] Core Validation Technique
Remote Validation in [Link] Core
[Link] Core MVC
Sesion in [Link] Core
[Link]
Attribute Routing in [Link] Core
[Link] Core CRUD Operations
Exception Handling in [Link] Core
Logging in .Net Core
Multiple Files Upload in [Link] Core MVC
Retrieve static files / images from wwwroot folder
Microservices in .Net Core
Globalization Localization
Create Razor Pages Application
Learn Razor Pages in [Link] Core
In this tutorial we will learn how to create a simple [Link] Core
Web Application step by step to understand over all structure of
[Link] core project folders, pages, wwwroot, code behind etc.
Setp 1:
Open Visual Studio 2017, Select File => New => Project
Step 2:
Select "Web Application" then click "OK"
Step 3:
As we can see the following [Link] Core default stricture created
by visual studio. Now let’s understand each folder, files and how
they work.
Razor Page Application Structure
Now if you notice there is something called “Pages” folder which
contain many razor pages inside, razor pages are just like web form
in earlier version, so in this new pages we have [Link] , means
code behind file like we used to have in [Link]
The thought behind this razor page was to keep all functionalities
keep in one place for that particular page, so for small project or
website this may be good, but I personally don’t like the idea,
because for many reason, one strong reason is that this approach
may make “re-usability of code” more difficult, and writing all in one
place may look dirty.
While creating a page under pages folder, it gives an option to
select a model and one of CRUD operation.
But there was a plan for this type page design, razor page is
lightweight, very flexible & cross platform compatible.
In next tutorial we talk about handler methods and lifecycle of razor
page request in [Link] Core application.
Here are the few things like default files, folders you may find new
in [Link] development
“wwwroot” for creating static file
[Link] a json file
[Link]
[Link] for bundling and minification
[Link] etc.
so let’s learn them one by one.
wwwroot directory in [Link] Core
what is wwwroot folder in [Link] core?
When we create any [Link] Core project, the wwwroot folder is
created by default, this folder is basically for all types of static files
like html, css, js, images etc.
Any other type of [Link] applications we can store any static files
in root, or in any other folder under root, and can be served from
there. This has been changed in [Link] Core. Now we can store
any static files under wwwroot folder only, all other files are blocked
on http request.
[Link] in [Link] Core
How to use [Link]?
Now you may not find any [Link] file in [Link] Core
application, but to keep all standard configuration information like
database connection string, SMTP information or any other custom
configuration you may need to keep, now all will go in a file called
[Link], but you still can continue with custom
configuration framework if you have already used in your
application.
How to add new keys in [Link]?
[Link] always contain values with key value pair separated
with a colon like “Key”: “Value”
Now for each key you can have a single value or multiple values with
a set of keys. you can write this way “section-key” :{ “key1”:”value1”,
“key2”:”value2”}
How to read values from [Link] file?
There are multiple ways to read value from [Link] file
First we learn simple way, like how we used to read value from
[Link] appsettings section.
In [Link] Core we need to refer a
namespace [Link]; and then use
IConfiguration to read the value from [Link] file.
In controller constructor we need to set the local IConfiguration
property this way.
private readonly IConfiguration config;
public studentController(IConfiguration configuration)
{
config = configuration;
}
Here is the code
using [Link];
public class studentController : Controller
{
private readonly IConfiguration config;
public studentController(IConfiguration configuration)
{
config = configuration;
}
public IActionResult index()
{
// Method 1 to read value
string _dbCon1 =
[Link]("DbConnectionConfig").GetSection("Databa
seName").Value;
// Method 2 to read value
string _dbCon2 =
[Link]<string>("DbConnectionConfig:DatabaseName")
;
return View();
}
}
Method 2
There is another we can read values using custom class from
[Link], like how we used to read using custom
configuration in earlier .net version
See this code Illustration
using [Link];
using [Link];
public class HomeController : Controller
{
private readonly DbConnection dbconfig;
public HomeController(IOptions<DbConnection> dbcon)
{
dbconfig = [Link];
}
}
Make sure you have registered the new section in ConfigureService
method of [Link]
[Link]<DbConnection>([Link]("DbCon
nectionConfig"));
ConfigureService Method of [Link]
How to use [Link] in [Link] Core
What is [Link] ?
[Link] file is the entry point of the application. This will be executed
first when the application runs, there is a public static void Main method,
Whatever code you write inside that method will be executed in that
same order, In [Link] core application we normally call all "hosting
related setting and [Link] file methods" from that Main() method.
Can we run application without [Link] file ?
No, it will give an build error, will not allow to run the application.
In [Link] Core there is a new way to build web host configuration.
Now we can set defaults of the web host configuration using
[Link]()
This is how the [Link] file look like
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
[Link](args)
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}
In public static void Main() of Program class where we can create a
host for the web application, earlier tutorial we have explained
about [Link] core [Link] class
var host = new WebHostBuilder();
// Now
IWebHostBuilder host = [Link](args)
//CreateDefaultBuilder is a static method now create the
new instance
// finally call
[Link]();
How to use bundleconfig in [Link] Core
Bundleconfig in [Link] Core
Bundling and minification in [Link] Core : In earlier version of
[Link] we had a [Link] file with a static RegisterBundles
method, where we could add any additional files for bundling and
minification, but in .net Core there is no [Link] file,
instead there is a [Link], a plain text file, which works
very differently.
When you create a new [Link] Core project a [Link] file
automatically added to project
This is how the default file look like
[
{
"outputFileName": "wwwroot/css/[Link]",
"inputFiles": [
"wwwroot/css/[Link]"
]
},
{
"outputFileName": "wwwroot/js/[Link]",
"inputFiles": [
"wwwroot/js/[Link]"
],
"minify": {
"enabled": true,
"renameLocals": true
},
"sourceMap": false
}
]
inputFiles : takes comma separated name of all the files, here is an
example how you can add multiple file in that array.
"inputFiles": [
"wwwroot/js/[Link]",
"wwwroot/js/[Link]",
"wwwroot/js/[Link]",
]
External utility for bundling and minification in
[Link] Core
There are many tools for bundling and minification in [Link] Core,
There some tools are from open source technologies and some are
developed by Microsoft.
Here we show how to work with few of them
BundlerMinifier, WebOptimizer, Webpack, Gulp
BundlerMinifier
BundlerMinifier is the first choice for [Link] Core
application for bundling and minification, read more about
this Utility. It has following features
o Bundle CSS, JavaScript or HTML files into a single output
file
o Supports MSBuild for CI scenarios
o Supports Command line
o Minify individual or bundled CSS, JavaScript and HTML files
You can install [Link] using NuGet.
WebOptimizer WebOptimizer is an [Link] Core middleware
for bundling and minification of JavaScript, CSS files at
runtime
// in configureServices() method
[Link]();
// in Configure() method
[Link]();
[Link]();
install [Link] using NuGet
Gulp
Gulp is a JavaScript task runner which can automate many
common tasks of a website like minification, checking js
errors, bundling of various js and CSS files, optimizes images
etc.
Here is a nice article on How to Use Gulp in [Link] Core
[Link] in [Link] Core
What is Startup class in [Link] Core?
Startup class or [Link] file is generated as part of the default
[Link] Core template. Startup class is the entry point of
application. It configures the request pipeline that handles all
requests made to the application.
[Link] is used for configuration & Startup Class is mandatory in
[Link] Core application
Can we rename the startup class to some other name?
Yes, Finally this [Link] is used in Program class for hosting the
application, So renaming this class will not make any difference.
Startup Class Constructor & IConfiguration
Setting up IConfiguration in Startup constructor
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
In Startup file you can see an example of dependency injection
ConfigureServices Method in [Link]
In ConfigureService method we can configure any service in that
application, to do that all service to be added in IServiceCollection
For example you can see how below methods are added
[Link](); this was added by default
[Link]<DbConnection>([Link]("DbCon
nectionConfig"));
public class Startup
{ // This method gets called by the runtime. Use this
method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
[Link]();
[Link]<DbConnection>([Link]("
DbConnectionConfig"));
}
}
In above example we are try to configure a DbConnectionConfig
class we read information from [Link] class, so we want
when service starts, all configuration information to be available in
custom configuration class
Configure Method in [Link]
This method gets called by the runtime. Use this method to
configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
if ([Link]())
{
[Link]();
[Link]();
}
else
{
[Link]("/Home/Error");
}
DbConnectionString =
[Link]("Server={0};Database={1};
User ID={2};Password={3};Trusted_Connection=False;
MultipleActiveResultSets=true;",
Configuration["DbConnectionConfig:ServerName"],
Configuration["DbConnectionConfig:DatabaseName"],
Configuration["DbConnectionConfig:UserName"],
Configuration["DbConnectionConfig:Password"]);
[Link]();
[Link](routes =>
{
[Link](
name: "default",
template:
"{controller=Home}/{action=Index}/{id?}");
});
}
Kestrel web server in [Link] Core
[Link] Core Kestrel web server configuration tutorial for
beginners.
What is Kestrel Web Server?
Kestrel is open-source, event-driven, asynchronous I/O based web
server for hosting [Link] applications. it uses async I/O library
called libuv primarily was developed for [Link]
When we create any [Link] Core Projects, the [Link] Core
templates include Kestrel web server by default
Kestrel web server is included in the project as a Nuget
package [Link]
Why Kestrel when there was IIS
If you have been developing [Link] application for some long time,
then you may have a question what was the necessity of Kestrel
when there was well established web server IIS!
First reason is, IIS is limited to windows OS only, but now [Link]
core was designed to be hosted on other platform like LINUX, Mac,
so there was a need for a web server that can run on different OS
apart from windows.
Kestrel provides much efficient request processing to [Link] Core
applications, which helps improving the application performance.
Kestrel Web server Characteristic
Kestrel is cross-platform, runs in Windows, LINUX and Mac.
Kestrel webserver can supports SSL
Using Kestrel, we cannot have multiple applications
running on same port
Kestrel is a very light weight webserver that does not have
every advanced features of webservers like IIS
But Kestrel is much faster compare to IIS
How to use Kestrel Web server?
We can use Kestrel Webserver just by calling the method
UseKestrel() in host builder of Program file.
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
[Link](args)
.UseKestrel()
.UseIISIntegration()
.UseStartup<startup>()
.Build();
}
Notice .UseKestrel() method in above static BuildWebHost method,
Specify Kestrel server to be used by web host. that's how kestrel
server is configured in an [Link] Core application.
How to start [Link] Core app with Kestrel
In [Link] core application when we press F5 to run the application
on local machine, it uses “IISExpress” as web server, if you want to
use Kestrel web server to run your application on local machine, you
just need to click on drop-arrow icon next to “IISExpress” , then
select the application name, see the picture below.
Now if you click on F5, your Kestrel web server will start, and your
web page will open up in default browser.
You will see a black DOS window will open up, the window will
display all hosting related information.
If you want to shut down the Kestrel web server, you can either
close the window or press "control + C" to shut down.
Run using Dotnet CLI
You also can run the application from command prompt, just to open
command window and then run the following command.
dotnet run
Before running the above command make you go to project folder
location in your DOS window.
What is Razor Page in [Link] Core?
Razor Page ([Link]) in [Link] Core is just like [Link] in earlier
version of [Link], Razor Page is built on top of [Link] Core MVC,
but you don’t need any previous MVC knowledge, razor pages are
very light weight and easy to work with.
Create Razor Page
Right click on Page folder => Add => Razor Page=>
There you probably see three options Razor Page, Razor Page using
Entity Framework and Razor Page using Entity Framework (CRUD)
You can start with simple empty page.
File name cannot start with underscore (_)
File should have .cshtml extension
First line in the file should be @page
Here are few characteristic of Razor Pages in [Link] Core .
[Link] Core Razor Pages is a page-centric framework for
building dynamic, data-driven web application.
Razor Pages can support cross platform development and
easily can be deployed on different operating systems like
Windows, UNIX and Mac.
The Razor Pages is very lightweight and flexible. It
provides full control over rendering HTML as per need,
easy to work with.
The razor page framework is built on top of [Link] Core
MVC; anyone can work with [Link] core pages with having
any previous MVC Knowledge
Every page has a Model, actually pages are inherited from
PageModel
Razor Page Models
A l l p a g e m o d e l a r e i n h e r i t e d f o r m PageModel c l a s s .
Add Property in Model
Notice every property in model has to have a BindProperty attribute.
, then only you can access this property while form in submitted,
BindProperty is new in [Link] Core, was not there in earlier
version.
using [Link];
using [Link];
namespace [Link]
{
public class IndexModel : PageModel
{
[BindProperty]
public string Email { get; set; }
}
}
This is how we call the model reference in chtml page
@page
@model IndexModel
@{
ViewData["Title"]="Page Title Here"
}
When you create razor page with model, a code behind file is
created
[Link]:
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace [Link]
{
public class IndexModel : PageModel
{
public void OnGet()
{
}
}
}
Working with Razor Page Forms
[Link]: here is a simple form with three fields, the way we
used to write in classic asp, php etc
<form method="post">
<div>Name: <input name="name"/> </div>
<div>Name: <input name="email"/> </div>
<div>Name: <input name="mobile"/> </div>
<div> <input type="submit"/> </div>
</form>
Once you submit the form, you can access the submitted values in
your codebehind OnPost() method
[Link]:
public void OnPost()
{
var name = [Link]["name"];
var email = [Link]["email"];
var mobile = [Link]["mobile"];
// now you have all submitted values in local variables
}
You should also read the Form in Razor Page to know more about
PageModel, Handler Methods, Leveraging Model Binding, Handler
method parameters etc.
Partial view in [Link] Core Razor Page
[Link] Core Razor Partial Page
Partial view is just like a razor page file, some people call it partial
page, only difference that partial view can be a part of main page,
we can write html and server side code in partial view, in one page
we can have any number of partial views.
Add partial view in razor page
You can create a partial view under Pages folder or in any other sub
folder.
Here we have created a partial view called "_menu" under
pages=>shared folder.
In above example we have created a simple partial view where we
want to add all common menu items
Remember Partial view doesn't have an @page directive at the top
File Name: _menu
<div>
Link 1 | Link 2 | Link 3 | Link 4
</div>
Now calling this partial view from any razor page
@[Link]("shared/_menu")
In [Link] Core 2.1 there is new partial tag helper.
The name attribute takes the name of partial file, with or without
the file extension, it works both ways
<partial name="shared/_menu" />
Html helper also offers 3 other methods for implementing partial
view, RenderPartial , RenderPartialAsync and PartialAsync
@{ [Link]("shared/_menu"); }
Partial Pages Location and Naming Convention
There is no rule for partial view location and naming convention, you
can give any name, but as a standard practice we usually use
underscore at beginning for all naming partial view name, for
example you can see the above partial view name is "_menu".
Where to create the file?
You can create partial view in anywhere under “Pages”, But the best
practice would be to create a folder with name “shared” or “partial”,
then create all partial view under that folder.
There is also an advantage of keeping all partial views under one
folder; you can configure the location in ConfigureServices method
under [Link] file.
public void ConfigureServices(IServiceCollection services)
{
[Link]().AddRazorOptions(options =>
{
[Link]
.Add("/Pages/shared/{0}.cshtml");
});
}
Now while accessing the partial view, you don’t need to provide the
full path like @[Link]("shared/_menu"), you can
call @[Link]("_menu"), Automatically razor page view engine
will search that particular folder for all views
Razor pages partial view with model example
We can use model with partial view in [Link] core razor page ,
Here we learn how to work with strongly type partial view (with
model) in [Link] core razor page application.
In this example we have created following items
One content razor page called "[Link]" with
AboutModel:PageModel [Link]
One partial view "_studentQuery" with a form to capture
student data
One model class called student
Now we see how to use student model in partial view _studentQuery
then call that partial view from main page [Link]
Step 1:
Create Student Model class with few properties
public class Student
{
public string Name { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
}
Step 2:
Create partial view with name "_studentQuery", then add the model
reference, and create a simple form to capture student data.
@model [Link];
<form method="post">
Name: <input asp-for="Name" />
Mobile: <input asp-for="Mobile" />
Email: <input asp-for="Email" />
<input type="submit" value="Join" />
</form>
Step 3:
Now create the main content page [Link] , and call the partial
view with model reference like @[Link]("_studentQuery",
model:[Link])
@page
@model AboutModel
@[Link]("_studentQuery", model:[Link])
Notice in above code, [Link] is actually [Link]
So we need to create a property of Student type in AboutModel class
Step 4:
In [Link] file capture the submitted data
public class AboutModel : PageModel
{
public Student Student { get; set; }
public void OnGet()
{
Message = "Your application description
page.";
}
public void OnPost()
{
string _email = [Link]["Email"];
}
}
Hope you understood how to use strongly type partial view in
[Link] core razor page
Razor Page Methods in [Link] Core
In our earlier Tutorial we have explained how to create a Razor Page
project step by step. So now talk about handler method and Async
methods in [Link] core razor page.
[Link] Core Razor Page has some methods that are automatically
executed whenever we make a Request . There is some naming
convention used by Razor Pages framework, which helps to select
the appropriate handler method to execute.
Handler Methods in Razor Pages
Here are some standard methods of razor page codebehind [[Link]]
public void OnGet()
{
Message = "OnGet()";
}
public void OnPost()
{
Message = "OnPost()";
}
public void OnPut()
{
Message = "OnPut()";
}
Above methods are always executed when we request the page, All
method name follows standard naming convention.
Default Naming Convention
default convention of page methods (that are automatically executed
on page request)
"On" + HTTP verb used for the request
So all verbs are prefixed with "On" are the default methods name,
Like OnGet(), OnPost(), OnPut(), OnDelete() etc.
All Handler methods in razor page also have optional asynchronous
equivalents method like OnGetAsync(), OnPostAsync() etc. Now you
do not need to add the Async suffix
You can have either of these two methods in same razor page codebehind
[[Link]]
public void OnGet()
{
Message = "OnGet()";
}
Or
public void OnGetAsync()
{
Message = "OnGetAsync()";
}
Writing both will throw “InvalidOperationException: Multiple handlers
matched” exception, because both handlers are same, one with
Async one without.
Note: even if one method takes parameter and other one without
parameter still same exception will be thrown, means if you have
OnGet(string parameter1) and OnGetAsync() still won’t work, it’s
still considered as multiple handlers on same page.
Custom method in Razor Page [Link] Core
So far we have seen how to deal with standard methods, now we
learn how to write custom method in [Link] core razor page.
We can give any name to method as per our business requirement
Let's assume we need to create a registration form for company's
annual function, here we create a simple registration form
<form method="post">
Name: <input type="text" name="FullName" />
<button asp-page-handler="Register">Register</button>
</form>
Now in code behind we have to write a custom method to capture
the data, for method name we have to follow some naming
convention, method name always has to be like "OnPost" + asp-
page-handler value.
So here name should be OnPost + Register= OnPostRegister()
public void OnPostRegister()
{
var name = [Link]["FullName"];
// now you have all submitted values in local variables
}
We also can make Async method
"OnPost" + asp-page-handler value + Async
public void OnPostRegisterAsync()
{
var name = [Link]["FullName"];
// now you have all submitted values in local variables
}
But remember we can't have both methods on same page, even with
different signature, then that will throw an exception for multiple
handlers.
Handling Multiple Submit Buttons In Razor Pages
Now learn how to deal with multiple submit button with real time
example
Here we have designed a simple form; we want to capture the
training request from our employees, who want to learn which
subject! (You probably thinking this could have been done different
ways, true! this just to give an example of multiple submits!)
<form method="post">
<input type="submit" value="[Link]" asp-page-
handler="Aspnet" asp-route-valuecount="10" />
<input type="submit" value="[Link] MVC" asp-page-
handler="Aspnetmvc" asp-route-valuecount="12"/>
<input type="submit" value="[Link] Core" asp-page-
handler="Aspnetcore" asp-route-valuecount="15"/>
<input type="submit" value="LINQ" asp-page-handler="Linq"
asp-route-valuecount="20"/>
<input type="submit" value="HTML" asp-page-handler="Html"
asp-route-valuecount="10"/>
</form>
Now in code behind you can write multiple handler method, each
time form is submitted a different method is getting executed, so
based method you can update database, write complex business logic
to decide further action for user.
public void OnPostAspnet(int valuecount)
{
ViewData["ActionMessage"] = $"Aspnet
{valuecount}";
}
public void OnPostAspnetmvc(int valuecount)
{
ViewData["ActionMessage"] = $"AspnetMVC
{valuecount}";
}
public void OnPostAspnetcore(int valuecount)
{
ViewData["ActionMessage"] = $"AspnetCore
{valuecount}";
}
public void OnPostLinq(int valuecount)
{
ViewData["ActionMessage"] = $"LINQ
{valuecount}";
}
public void OnPostHtml(int valuecount)
{
ViewData["ActionMessage"] = $"Html
{valuecount}";
}
Please make sure method naming convention is followed.
[Link] Core Razor Page Form Example
Now we learn about How to work with Form in [Link] Razor Pages,
PageModel, Handler Methods, Leveraging Model Binding, Handler
method parameters etc.
Create Form in Razor Page
In razor page we can create form in two ways
1. Using simple html form tag
2. Using MVC form syntax
With both type of form tag we can work using model and non-
model.
Here we learn both form tag and with & without Model
Razor Page Form without Model Example
Example 1 .cshtml: here is a simple html form tag without
Model with three fields, the way we used to write in classic asp,
php etc
<form method="post">
<div>Name: <input name="FullName" /> </div>
<div>Email: <input name="Email" /> </div>
<div>Mobile: <input name="ContactNumbers" /> </div>
<div> <input type="submit" /> </div>
</form>
Example 2 .cshtml: here is an example Using MVC form without
Model syntax with three fields.
@using ([Link]([Link]))
{
<div class="s1">
<div>Full Name</div>
@[Link]("FullName", new { @class = "searchTxt" })
</div>
<div class="s1">
<div>Contact Numbers</div>
@[Link]("ContactNumbers", new { @class =
"searchTxt"})
</div>
<div class="s1">
<div>Email</div>
@[Link]("Email", new { @class = "searchTxt" })
</div>
<div>
<input type="submit" value="Contact" />
</div>
}
Razor Page Form with Model Example
Create Model for Razor Form
First we create a simple Model with few properties , each property
has to have a [BindProperty] attribute
public class ContactModel : PageModel
{
[BindProperty]
public string FullName { get; set; }
[BindProperty]
public string ContactNumbers { get; set; }
[BindProperty]
public string Email { get; set; }
}
Example 1 .cshtml:
here is a simple example of html form tag with Model with three
fields.
Now if you notice I have specified fields in two different ways, first
one Using MVC style and other one using asp-for="propertyname",
both works fine!
<form method="post">
<div>@[Link](m => [Link])</div>
<div>Email: <input asp-for="Email" /> </div>
<div>Mobile: <input asp-for="ContactNumbers" /> </div>
<div> <input type="submit" /> </div>
</form>
Example 2 .cshtml:
Using MVC form syntax with three fields
@using ([Link]([Link]))
{
<div class="s1">
<div>Full Name</div>
@[Link](m => [Link]) </div>
<div class="s1">
<div>Contact Numbers</div>
@[Link](m => [Link]) </div>
<div class="s1">
<div>Email</div>
@[Link](m => [Link])
</div>
<div>
<input type="submit" value="Contact" />
</div>
}
Razor Form Submission
Once you submit the form, you can access the submitted values in
your codebehind OnPost() method
Now here we have given two examples
This one will work only if you have Model associated with the form
[Link]:
public void OnPost()
{
var name = FullName;
var email = Email;
var mobile = ContactNumbers;
// now you have all submitted values in local variables
}
This example will work in both situations, with Model and without
Model
Still you can access properties using [Link]["fieldName"]
public void OnPost()
{
var name = [Link]["FullName"];
var email = [Link]["Email"];
var mobile = [Link]["ContactNumbers"];
// now you have all submitted values in local variables
}
Handling Multiple Actions For Form in Razor Page
In some situation you may need to have multiple action buttons, in
such situation you can write separate named handler methods, and
in action tag helper specify the handler method name.
<form method="post">
<button asp-page-handler="Register">Register</button>
<button asp-page-handler="Request">Request Info</button>
</form>
Now in codebehind specify the method name with OnPost Prefix or
Async Suffix
public void OnPostRegister()
{
var name = [Link]["FullName"];
// now you have all submitted values in local variables
}
public void OnPostRequest()
{
var name = [Link]["FullName"];
// now you have all submitted values in local variables
}
Now if you notice above methods name "OnPost" + value of asp-page-
handler
You should also read razor pages handler methods in [Link] Core
[Link] Core validation Example
[Link] Core Validation Tutorial for beginners step by step
[Link] Core Razor validation Technique
When you accept data input from user then save the data in
database, you must ensure that all incoming values that user has
entered, are matching with data type, length specified in database,
otherwise that will produce error and won’t be able to save the data
in database.
So, you have to validate before processing data.
There are differ ways you can validate data in [Link] Razor Form
Razor page framework are built on MVC Framework, so it supports
following input validation framework.
Validation using DataAnnotation Attributes
Vlidation using Tag Helpers
jQuery Unobtrusive Validation
Server Side Validation Technique
Model Validation using DataAnnotation Attributes
Validation using DataAnnotation Attributes in [Link] Core works in
the same way we used to perform validation in earlier [Link] MVC .
All validation classes are inherited from ValidationAttribute, You
need to use [Link] Namespace
Validation Attributes in [Link] Core
Required
Indicates that the value must be provided for this field,
else display error message
Range
Specify the minimum and maximum values of a range, so
user must provide a value within that range
Compare
Compare the value of two fields, or with a fixed specified
value
StringLength
Sets the maximum number of string characters allowed
MaxLength
Sets the maximum length, number of characters can be
accepted
MinLength
Sets the minimum length, number of characters can be
accepted
RegularExpression
Checks if the value matching against the specified regular
expression
Remote
It helps enabling client-side validation against a server-
side code, like checking database to see if a partial email
id is already in use
Client side validation in Razor [Link] Core
In form you also can provide client side validation support using
jQuery.
Here we design a simple form to show how to display
<form method="post">
<input asp-for="FullName" />
<span asp-validation-for="FullName"></span>
<input asp-for="Email" />
<span asp-validation-for="Email"></span>
<input asp-for="ContactNumbers" />
<span asp-validation-for="ContactNumbers"></span>
<input type="submit" value="Submit" />
</form>
If you check how the html look like after rendering, notice data-
val="true", if set data-val="false" then validation won't happen
<form method="post">
Name:<input type="text" data-val="true" data-val-length="5-
60 character" data-val-length-max="60" data-val-length-
min="5" data-val-required="Full Name Required"
id="FullName" name="FullName" value="" />
<span class="field-validation-valid" data-valmsg-
for="FullName" data-valmsg-replace="true"></span>
Email: <input type="email" data-val="true" data-val-
email="Invalid email" data-val-required="Email required"
id="Email" name="Email" value="" />
<span class="field-validation-valid" data-valmsg-
for="Email" data-valmsg-replace="true"></span>
Mobile: <input type="text" data-val="true" data-val-
length="10-14 character" data-val-length-max="14" data-val-
length-min="10" data-val-required="Contact Numbers
Required" id="ContactNumbers" name="ContactNumbers"
value="" />
</form>
Make sure you have added following jquery files as reference in your
page
@section scripts
{
<script src="~/lib/[Link]"></script>
<script src="~/lib/[Link]"></script>
<script src="~/lib/[Link]"></script>
}
[Link] Core Model Validation Example
Server side validation: Sometimes it’s necessary to implement
server side validation, because we cannot depend on client side
validation completely, there are ways to disable client side script,
sometimes they are not supported by different version of different
browsers, sometimes bugs can cause problem, so in framework there
is also an easy way to check server side validation.
public class ContactModel : PageModel
{
[Required(ErrorMessage = "Full Name Required")]
[StringLength(60, ErrorMessage = "5-60 character",
MinimumLength = 5)]
[BindProperty]
public string FullName { get; set; }
[Required(ErrorMessage = "Contact Numbers
Required")]
[StringLength(14, ErrorMessage = "10-14 character",
MinimumLength = 10)]
[BindProperty]
public string ContactNumbers { get; set; }
[EmailAddress(ErrorMessage = "Invalid email")]
[Required(ErrorMessage = "Email required")]
[BindProperty]
public string Email { get; set; }
public void OnGet()
{
Message = "Your application description page.";
}
public void OnPost()
{
string _email = [Link]["Email"];
}
}
In every PageModel validation error is added to
ModelStateDictionary, and you can access the dictionary result using
ModelState of PageModel class.
ModelState has a property called IsValid, which indicates if
validation check is successful, if not the IsValid property become
false.
Here is how you can check the validation at server side
public IActionResult OnPost()
{
if ([Link])
{
// add data in database
var fullName = FullName;
var contactNumbers = ContactNumbers;
var email = Email;
// then redirect to success page
}
else
{
// redirect to validation page
}
}
[Link] Core Remote Validation Example
Remote validation is basically validating data with database or any
other external web services while user entering data in text box,
making an ajax call to server side code to check if the input is valid
or else display the error message immediately.
Here I have written an example of Remote Validation Implementation
in [Link] Core
Remote validation in [Link] Core Razor Pages
What is Remote validation in [Link] Core?
Remote validation is a technique of validating data with database or any
other external web services while user entering data in text box, making
an ajax call to server side code to check if the input is valid or else
display the error message immediately
Remote validation example in [Link] core
step by step
Story behind implementation
We have created a simple form for accepting student registration for
sports event, so apart from student name and mobile number we are also
accepting a unique code as their choice, but we need to validate the code
with backend server to ensure that the same code has not been taken by
some other student. , and we have to check that at the time of
registration only.
Step 1:
Create a form with following fields like FirstName, LastName, Email
and StudentCode, StudentCode is the field where we experiment Remote
validation.
<form asp-controller="student" asp-action="index"
method="post"> <div asp-validation-summary="ModelOnly"
class="text-danger"> </div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"> </label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger">
</span>
</div>
<div class="form-group">
<label asp-for="LastName" class="control-label"> </label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger">
</span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"> </label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger">
</span>
</div>
<div class="form-group">
<label asp-for="StudentCode" class="control-label">
</label>
<input asp-for="StudentCode" class="form-control" />
<span asp-validation-for="StudentCode" class="text-
danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save Student"
class="btn btn-default" />
</div>
</form>
Step 2:
Make sure you have added following jquery file reference, so that
ajax request works properly
@section scripts
{
<script src="~/lib/[Link]"></script>
<script src="~/lib/[Link]"> </script>
<script src="~/lib/[Link]">
</script>
}
Step 3:
Now we create the model with all above fields, and notice how we are
setting Remote attribute on StudentCode property
public class StudentModel
{
public int StudentId { get; set; }
[Required(ErrorMessage = "Firstname Required")]
[StringLength(50, ErrorMessage = "5 to 50 characters.",
MinimumLength = 3)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Lastname Required")]
[StringLength(50, ErrorMessage = "5 to 50 characters.",
MinimumLength = 3)]
public string LastName { get; set; }
[Required(ErrorMessage = "Email Required")]
[EmailAddress(ErrorMessage = "Invalid email")]
public string Email { get; set; }
[Required(ErrorMessage = "Code Required")]
[Remote("ValidateCode","student", ErrorMessage = "Please
enter a valid code")]
public string StudentCode { get; set; }
}
This is how you call the method with Remote attribute
[Remote("MethodName","ControllerName", ErrorMessage = "Error
Message")]
Step 4:
Now we write the method in server side code to interact with
database or any external web service, this is the place where we
check if the code is already exist in database
public IActionResult ValidateCode(string code)
{
string result;
// here you can check the code with database
if (code == "wtr1")
{
result = "Valid code";
}
else
{
result = "Invalid code";
}
return Json(result);
}
Note:
Here we have not connected with database or web service, we simply
checked with a hardcoded value “wtr1”, you can replace that code
with your database call or web service call
[Link] Core MVC Project with Database
Example
[Link] Core MVC for Beginners Step by Step, in this tutorial we
learn how to develop Model View Controller Application using
[Link] Core Framework.
Before you learn MVC in [Link] Core, We suggest you to have good
understanding about Model View Controller in [Link] , because in
this article we talk about only what we implement differently in
[Link] Core.
Here are the steps we perform to create an [Link] Core MVC
application with Entity Framework Core as Data Access Layer
Create an [Link] Core MVC Application
Create new Controller for Student
Model for Student with property Validation
A Razor View for Student, where we can add new student
and display the list
A new Entity for Student and a Table in database
Implement Code First approach in Entity Framework
Finally Create new student and display them all on screen
Creating [Link] Core MVC Project Step by
Step
Open Visual Studio 2017 and above then select new project, under
"Web" select ".Net Core"
Now there are different types of [Link] Core Web Application, Select
Model View Controller
Basic structure of [Link] Core MVC Application, here we set up student
model, view and controller
Model, View, Controller in [Link] Core
Model We create a new model for Student, we name it StudentModel
using [Link];
using [Link];
namespace [Link]
{
public class StudentModel
{
[Required(ErrorMessage = "Firstname Required")]
[StringLength(50, ErrorMessage = "5 to 50
characters.", MinimumLength = 3)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Lastname Required")]
[StringLength(50, ErrorMessage = "5 to 50
characters.", MinimumLength = 3)]
public string LastName { get; set; }
[Required(ErrorMessage = "Email Required")]
[EmailAddress(ErrorMessage = "Invalid email")]
public string Email { get; set; }
public string Mobile { get; set; }
public List<Student> Students { get; set; }
}
}
View
Now we design view (razor) where we want to capture new student
data and display the student list.
Here are some important tags for designing form in [Link] Core
Razor.
Please notice how syntax is different than earlier [Link] MVC
Form design in [Link] Core Razor Syntax
Controller <form asp-controller="controllerName"/>
Action <form asp-action="actionName"/>
Method <form method="post"/>
Field <input asp-for="fieldName" />
Validation Message <span asp-validation-for="fieldName" />
Submit Button <input type="submit" />
Controller
In case you need to read any type of configuration information from
[Link] file, this is how you can get the configuration
information in controller.
Also there is another way to read the configuration
from [Link] information into DbContext
Here we create a new controller, where we can add a new student
and display the list of student
using [Link];
using [Link];
using [Link];
using [Link];
/// <summary>
/// Written by [Link]
/// </summary>
namespace [Link]
{
public class studentController : Controller
{
private readonly IConfiguration config;
public studentController(IConfiguration
configuration)
{
config = configuration;
}
[HttpPost]
public IActionResult index(StudentModel model)
{
Student _student = new Student();
_student.Firstname = [Link];
_student.Lastname = [Link];
_student.ContactNumber = [Link];
_student.Email = [Link];
using (StudentDTO dto = new StudentDTO())
{
[Link](_student);
}
return RedirectToAction("index", new { msg =
"New Student Added" });
}
[HttpGet]
public IActionResult index()
{
StudentModel model = new StudentModel();
using (StudentDTO dto = new StudentDTO())
{
[Link] = [Link]();
}
return View(model);
}
}
}
Work with Database in [Link] Core MVC
As we mentioned earlier in this example we will use Entity
Framework Core as Data Access Layer, So from our Data Transfer
Class we will call the instance of Entity DbContext Class.
Here is how our DataTransferObject called "StudentDTO" will look
like, learn about DbContext class EFContext() in entity framework
Core
using System;
using [Link];
using [Link];
/// <summary>
/// Written by [Link]
/// </summary>
namespace [Link]
{
public class StudentDTO
{
public Student AddStudent(Student s)
{
using (EFContext context = new EFContext())
{
[Link](s);
[Link]();
}
return s;
}
public List<Student> GetAllStudents()
{
List<Student> list = new List<Student>();
var context = new EFContext();
list = [Link]
.ToList<Student>();
return list;
}
}
}
How to use Session in [Link] Core
What is session in [Link] ?
Session management in [Link] is a technique to store and retrieve
information from session object , we normally store user specific
data in session object , so one user login we can use those
information in different pages where user keep browsing , we can
get those information from session object without going to database
every time
How to use session in [Link] Core
If you have experience in working with earlier [Link] version, you
must have worked with session object, but in [Link] core
implementation of session object is little different than earlier
version, in earlier [Link] we could straight away store and retrieve
any type of information from session just by using key-value
But in [Link] core you have to do some additional work to use
session object in application, you have to add session in middleware
pipeline
Step 1
Open [Link] file and inside ConfigureServices method register
the AddSession() method
public void ConfigureServices(IServiceCollection services)
{
[Link]();
}
Step 2
Now in Configure method call UseSession() method
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
[Link]();
}
Step 3
Now install [Link] utility from Nugget
Setting and retrieving values in [Link] Core Session object
In [Link] Core Session object there are 3 methods to set the
session value, which are Set, SetInt32 and SetString.
[Link]("sessionKeyString",
"WebTrainingRoom");
[Link].SetInt32("sessionKeyInt", 10);
And three methods for retrieving values from session , which are
Get, GetInt32 and GetString
string _sessionStringvalue =
[Link]("sessionKeyString");
int? _sessionIntValue =
[Link].GetInt32("sessionKeyInt");
So far we have seen how to use session object to store simple
information, but there is no straight way to store complex object in
[Link] core session.
Now we learn how to store complex object in session
How to store complex object in [Link] core session
So we have already understood there is no straight way of storing
complex data in session like we used to do in earlier [Link] version,
but here is how we can store complex data in [Link] core session
We have to create an additional class to add any object current session
using [Link];
using [Link];
public static class SessionHelper
{
public static void SetObjectAsJson(this
ISession session, string key, object value)
{
[Link](key,
[Link](value));
}
public static T GetObjectFromJson<T>(this
ISession session, string key)
{
var value = [Link](key);
return value == null ? default(T) :
[Link]<T>(value);
}
}
Now let's call the above methods to add and retrieve complex object
in session.
In following example we add a student object list in session and
retrieve from session
List<WtrStudent> _sList=new List<WtrStudent>();
[Link]([Link], "userObject",
_sList);
List<WtrStudent> _sessionList=
[Link]<List<WtrStudent>>([Link]
on, "userObject");
Hope you understood how to work with session in [Link]
core and storing complex object in [Link] core session
How to use bundleconfig in [Link] Core
Bundleconfig in [Link] Core
Bundling and minification in [Link] Core : In earlier version of
[Link] we had a [Link] file with a static RegisterBundles
method, where we could add any additional files for bundling and
minification, but in .net Core there is no [Link] file,
instead there is a [Link], a plain text file, which works
very differently.
When you create a new [Link] Core project a [Link] file
automatically added to project
This is how the default file look like
[
{
"outputFileName": "wwwroot/css/[Link]",
"inputFiles": [
"wwwroot/css/[Link]"
]
},
{
"outputFileName": "wwwroot/js/[Link]",
"inputFiles": [
"wwwroot/js/[Link]"
],
"minify": {
"enabled": true,
"renameLocals": true
},
"sourceMap": false
}
]
inputFiles : takes comma separated name of all the files, here is an
example how you can add multiple file in that array.
"inputFiles": [
"wwwroot/js/[Link]",
"wwwroot/js/[Link]",
"wwwroot/js/[Link]",
]
External utility for bundling and minification in
[Link] Core
There are many tools for bundling and minification in [Link] Core,
There some tools are from open source technologies and some are
developed by Microsoft.
Here we show how to work with few of them
BundlerMinifier, WebOptimizer, Webpack, Gulp
BundlerMinifier
BundlerMinifier is the first choice for [Link] Core
application for bundling and minification, read more about
this Utility. It has following features
o Bundle CSS, JavaScript or HTML files into a single output
file
o Supports MSBuild for CI scenarios
o Supports Command line
o Minify individual or bundled CSS, JavaScript and HTML files
You can install [Link] using NuGet.
WebOptimizer WebOptimizer is an [Link] Core middleware
for bundling and minification of JavaScript, CSS files at
runtime
// in configureServices() method
[Link]();
// in Configure() method
[Link]();
[Link]();
install [Link] using NuGet
Gulp
Gulp is a JavaScript task runner which can automate many
common tasks of a website like minification, checking js
errors, bundling of various js and CSS files, optimizes images
etc.
Here is a nice article on How to Use Gulp in [Link] Core
Attribute Routing Example in [Link] MVC
Attribute Routing in MVC C#
We have already explained routing concept in our earlier tutorial, if
you very new to routing concept then please read routing in [Link]
mvc first. Attribute routing is conceptually same but technically
implemented differently; you can alternative approach to
conventional routing.
Why Attribute Routing Useful?
In earlier version [Link] MVC we had a limitation of
defining SEO friendly Action Name, for example if we can have
action name as "attribute-routing" instead of "attributerouting" that
would be more appropriate for SEO.
How to Use Attribute Routing
Applying routing to any action using attribute is very simple!
Create a controller and an action, and then apply the attribute with
any SEO friendly name you want, notice how we have
applied [Route("attribute-routing")] in below IActionResult
[Route("attribute-routing")]
public IActionResult attributerouting()
{
return View();
}
Now probably you need to make one more changes in your Configure
method of [Link] file.
So open the startup file and make the following changes
Instead of
[Link]();
Replace with following code
[Link](routes =>
{
[Link](
name:"default",
template: "{controller=Home}/{action=Index}/{id?}");
});
Now you have successfully implemented Attribute Routing.
You can try accessing the page on browser by calling the attribute
value, like in this case controlloerName/attribute-routing
Razor Pages CRUD operations in [Link] Core
CRUD in Razor Page Application
In this tutorial we will learn how to create, read, update, and delete
(CRUD) in [Link] core razor page application, so we learn how work
with database.
While working with database from razor pages you can use any data
access mechanism like [Link], Entity Framework etc.
Here in example we will be using Entity Framework
Create a [Link] Razor Page Project, then add a new page, here in
example we have created a page for student, we learn how to add
new student then read, edit and delete on the same page.
Step 1: Create a page and design a form
Notice, in form, there is hidden field called StudentId, this will help
to differentiate new and existing student
<form method="post">
@[Link](m => [Link])
<div asp-validation-summary="ModelOnly" class="text-
danger"> </div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"> </label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-
danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName"
class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label">
</label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-
danger"> </span>
</div>
<div class="form-group">
<label asp-for="Mobile" class="control-label">
</label>
<input asp-for="Mobile" class="form-control" />
<span asp-validation-for="Mobile" class="text-
danger"> </span>
</div>
<div class="form-group">
<input type="submit" value="Save Student"
class="btn btn-default" />
</div>
</form>
Read Existing Students
@if ([Link] != null)
{
foreach (Student s in [Link])
{
<div style="padding:5px;">
@[Link] @[Link] <a
href="@[Link]("index","student",new
{ sid=[Link]})">Edit</a> | <a
href="@[Link]("delete","student",new
{ sid=[Link]})">Delete</a>
</div>
}
}
Step 2:
Create database connection details in [Link] and Entity
Framework class DbContext
"DbConnectionConfig": {
"DatabaseName": "MarketingDB",
"UserName": "masa",
"Password": "mapass",
"ServerName": "USER-PC"
}
Step 3:
Create a DTO class to interact with database using Entity
Framework, in this class we have written four methods AddStudent,
UpdateStudent, GetAllStudents, DeleteStudents, Learn IDisposable
Implementation
using System;
using [Link];
using [Link];
using [Link];
namespace [Link]
{
public class StudentDTO : IDisposable
{
public Student AddStudent(Student s)
{
using (EFContext context = new EFContext())
{
[Link](s);
[Link]();
}
return s;
}
public Student UpdateStudent(Student student)
{
Student _s = null;
using (EFContext context = new EFContext())
{
_s = [Link]
.Where(s => [Link] == [Link])
.FirstOrDefault<Student>();
if (_s != null)
{
_s.Firstname = [Link];
_s.Lastname = [Link];
_s.Email = [Link];
_s.ContactNumber = [Link];
[Link]();
}
}
return _s;
}
public List<Student> GetAllStudents()
{
List<Student> list = new List<Student>();
var context = new EFContext();
list = [Link]
.ToList<Student>();
return list;
}
public bool DeleteStudent(int stuid)
{
bool _isDeleted = false;
Student _s = null;
var context = new EFContext();
_s = [Link]
.Where(s => [Link] == stuid)
.FirstOrDefault<Student>();
if (_s != null)
{
[Link](_s);
[Link]();
_isDeleted = true;
}
return _isDeleted;
}
public Student GetStudent(int sid)
{
Student _s = null;
using (EFContext context = new EFContext())
{
_s = [Link]
.Where(s => [Link] == sid)
.FirstOrDefault<Student>();
}
return _s;
}
}
}
Step 4:
In PageModel public class studentModel:PageModel {}
First we create model properties
[BindProperty]
public int StudentId { get; set; }
[BindProperty]
[Required(ErrorMessage = "Firstname Required")]
[StringLength(50, ErrorMessage = "5 to 50
characters.", MinimumLength = 3)]
public string FirstName { get; set; }
[BindProperty]
[Required(ErrorMessage = "Lastname Required")]
[StringLength(50, ErrorMessage = "5 to 50
characters.", MinimumLength = 3)]
public string LastName { get; set; }
[BindProperty]
[Required(ErrorMessage = "Email Required")]
[EmailAddress(ErrorMessage = "Invalid email")]
public string Email { get; set; }
[BindProperty]
public string Mobile { get; set; }
[BindProperty]
public List<Student> Students { get; set; }
Setup property values in OnGet() method
public void OnGet()
{
int _id = Convert.ToInt32([Link]["sid"]);
Student _s = null;
using (StudentDTO dto = new StudentDTO())
{
[Link] = [Link]();
_s = [Link](_id);
if (_s != null)
{
[Link] = _s.StuId;
[Link] = _s.Email;
[Link] = _s.Firstname;
[Link] = _s.Lastname;
[Link] = _s.ContactNumber;
}
}
}
Finally When form submitted, we capture the value and update database
in OnPost() method
public IActionResult OnPost()
{
Student _student = new Student();
_student.Firstname = FirstName;
_student.Lastname = LastName;
_student.ContactNumber = Mobile;
_student.Email = Email;
_student.StuId = StudentId;
using (StudentDTO dto = new StudentDTO())
{
if (_student.StuId == 0)
{
[Link](_student);
}
else
{
[Link](_student);
}
}
return RedirectToPage("student", new{msg="updated"});
}
I hope you understood how to add, select, edit, delete data in
[Link] razor page application
Exception handling in [Link] Core
[Link] Core Error handling Example
Exception handling is one of the very important feature in
application development life cycle, that help us to deal with the
unexpected errors which could appear from our coding, server
connectivity, bad data, or any other situation, so there are many
different ways for handling such exception
Now we learn exception handling in [Link] core .
If you have not read our earlier exception handling in
[Link] tutorial, please read that, here we discuss different ways of
exception handling in [Link] core application only
Exception handling is also type of Middleware in [Link] Core
In this tutorial we will talk about three different ways of error
handling in [Link] Core
Error Handling with Try-Catch Block
Global Errors Handling with UseExceptionHandler
Middleware
Global Exception Handling with the Custom Middleware
[Link] core catch all errors
Try catch is common in all most all development practice, very easily
can implemented on every function or method you write.
Error Handling with Try-Catch Block
try
{
// here you write you code
}
catch (Exception ex)
{
here you get all exception details in Exception
variable, you can either log the error details or display
to user
}
finally
{
// is optional
}
Global Errors Handling with Middleware
We use Exception handling middleware UseExceptionHandler in
Configure method of [Link]
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
// write error handling code here
}
To understand if error handling is working properly let’s create some
error on PageModel class
public void OnGet()
{
throw new Exception("this is an exception");
}
The above code will throw error, will see how differently we can
catch the exception and log error details and display user friendly
error message .
[Link] core error development mode
We can implement different type of exception handling mechanism
for different environment like for development, staging, production
etc.
if([Link]() || [Link]())
{
[Link]();
}
else
[Link]("/error");
Now in above exception handling technique you will be able redirect
user to a error page with some messages, but this will not help you
to capture actual error details for logging or resolving the issue.
So now let's look at another way of capturing error details
Use of UseExceptionHandler
[Link](
options =>
{
[Link](
async context =>
{
[Link] =
(int)[Link];
[Link] = "text/html";
var ex =
[Link]<IExceptionHandlerFeature>();
if (ex != null)
{
var err = $"<h1>Error:
{[Link]}</h1>{[Link]}";
await
[Link](err).ConfigureAwait(false);
}
});
}
);
Global Exception Handling with Custom Middleware
Now we see how to write a custom middleware for error handling,
and how to access current HttpContext and error details associated
with that
using [Link];
using [Link];
using [Link];
namespace AspNetCoreWebApplication
{
public class WTRCustomMiddleware
{
private readonly RequestDelegate _next;
public WTRCustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
await [Link]("- Before Message - \n\
r");
await _next(context);
var ex = [Link]<IExceptionHandlerFeature>();
await [Link]("\n\r - After
Message - ");
}
}
Now create a Middleware Extensions class
public static class WTRCustomMiddlewareExtensions
{
public static IApplicationBuilder
UseWTRCustomMiddleware(this IApplicationBuilder builder)
{
return
[Link]<WTRCustomMiddleware>();
}
}
}
In above middleware you have HttpContext, so get the exception
details var ex =
[Link]<IExceptionHandlerFeature>(); Now call the
above custom middleware in Configure method of [Link]
[Link]();
[Link](async context =>
{
await [Link]("Welcome to
WebTrainingRoom!");
});
Now we see how to catch error status code like page not found,
internal server error etc.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
[Link]();
}
Now if try to access some unknown page on browser, you will get
following error message
Status Code: 404; Not Found
Above method is good enough to catch error status code and display
the error, but in application development sometimes you may want
to display the error to a different user friendly page with other page
navigation, in such situation you can use
UseStatusCodePagesWithRedirects().
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
[Link]("/Error", "?
statusCode={0}");
}
this method will redirect user to a different error page, where you
can show custom error message based on statusCode, alternatively
you also can create different error page for each code, and redirect
to page based on code.
Logging example in [Link] Core
[Link] Core Logging Example
Logging is one of the very important functionalities in software
development, [Link] Core Logging can be used for various reason,
but most of the time we use logging function for User Activity
logging and Error Logging, You can use logging anywhere you want.
In [Link] Core we have built-in logging apart from third party
logging utility like Log4net. [Link] Core logging framework is not
as feature-rich as third party libraries, So let’s understand how much
we can do with [Link] Core built-in Logging
[Link] Core Built-in Logging
Before we learn about Logging implementation in [Link] Core, let’s
understand important logging classes, interface and functions in
[Link] Core Framework.
Namespace [Link] . We learn about
ILoggingFactory, ILoggingProvider, ILogger, LoggingFactory Logging is
done using ILogger extension methods:
LogDebug()
LogInformation()
LogWarning()
LogError()
LogCritical()
[Link] core logging [Link]
Setting up code in [Link]
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
Now setup ILoggerFactory in Configure method of [Link]
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
[Link]([Link]("Logging"
));
[Link]();
//removed all other code for clarity
}
[Link] core logging dependency injection
We need to use ILogger, ILoggerFactory using dependency injection
in constructor
Now open your controller class and use dependency injection through
constructor, you can do that in two ways
public class homeController : Controller
{
ILogger _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
//you can have either one
public HomeController(ILoggerFactory loggerFactory)
{
_logger =
[Link](typeof(HomeController));
}
public IActionResult index()
{
_logger.LogInformation("just testing
LogInformation()");
_logger.LogError("There is no error, just testing
LogError()");
return View();
}
}
Log4net for [Link] core logging
How to use third party logging utility like Log4Net with [Link] Core.
Tough [Link] Core has built-in Logging mechanism, but I still
prefer Log4Net net because of many option of logging and easy to
implement.
Here are the few simple steps to implement Log4Net in your [Link]
Core application.
Step 1
Install Log4Net utility using NugetPackage
Right Click on your project => Manage NuGet Package =>
log4net [Link] core configuration
Step 2
Create a xml file in root of the application with name
"[Link]"
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="RollingFile" />
</root>
<appender name="RollingFile"
type="[Link]">
<file value="D:\[Link]" />
<layout type="[Link]">
<conversionPattern value="%-5p %d{hh:mm:ss} %message
%newline" />
</layout>
</appender>
</log4net>
</configuration>
Make sure you change the file tag value, mention your file path,
where you want file to be created.
Step 3
Now setup log4net Repository in [Link] file
public class Program
{
public static void Main(string[] args)
{
var log4netRepository =
[Link]([Link](
));
[Link](log4netRepository,
new FileInfo("[Link]"));
BuildWebHost(args).Run();
}
}
Step 4
Now open your controller class and setup _log4net local object, so
you can access all log4net methods in this controller, for example
we have called _log4net.Info() method in index.
public class HomeController : Controller
{
static readonly [Link] _log4net =
[Link](typeof(HomeController));
public IActionResult index()
{
_log4net.Info("Hello logging world log4net!");
return View();
}
}
Now run the application, and to check if log details written properly
in file you mentioned in <file value="D:\[Link]" /> tag
Hope this was helpful!
[Link] Core MVC File Upload Example
In this tutorial you will learn how to upload file in [Link] core ,
You will also learn how to retrieve those files and delete from folder
under wwwroot.
File Uploading Example in [Link] Core
First we design a form in razor view that will allow us to browse and
upload one or multiple images from local machine.
Form design in Razor View, Note: If you specify multiple in input file
field, which means it will allow multiple files to be selected and
uploaded.
<form method="post" enctype="multipart/form-data" asp-
controller="FileUpload" asp-action="index">
<div class="form-group">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="files" multiple />
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Upload" />
</div>
</div>
</form>
Add Middleware Service in Startup
You need to add following Middleware Service reference in
ConfigureServices method of [Link] file. In your
ConfigureService method there may be many other services already
added, so just add IFileProvider Service also.
using [Link];
using [Link];
public void ConfigureServices(IServiceCollection services)
{
[Link]<IFileProvider>(new
PhysicalFileProvider(
[Link]([Link](),
"wwwroot")));
[Link]();
}
Get file path in [Link] Core
To get folder reference in [Link] Core Controller you need to Add
IHostingEnvironment in Controller with DI
Now you need the folder reference where you want to save all
uploaded image files, and to get that you need an instance of
IHostingEnvironment, so in controller constructor we create the
instance using dependency injection
private readonly IHostingEnvironment _hostingEnvironment;
public fileuploadController(IHostingEnvironment
hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
File Upload Controller Code
Finally we write the controller code where we process the files
posted from image upload form in razor view.
Note: while creating FileStream object pass file name with folder
Path, if you pass only folder Path in FileStream, You may get
UnauthorizedAccessException while uploading file in [Link] core
application.
using [Link];
using [Link];
[HttpPost("FileUpload")]
public async Task<IActionResult> index(List<IFormFile>
files)
{
if (files == null || [Link] == 0)
return Content("file not selected");
long size = [Link](f => [Link]);
var filePaths = new List<string>();
foreach (var formFile in files)
{
if ([Link] > 0)
{
// full path to file in temp location
var filePath =
[Link](_hostingEnvironment.WebRootPath,
"userimages");
[Link](filePath);
var fileNameWithPath =
[Link](filePath,"\\",[Link]);
using (var stream = new
FileStream(fileNameWithPath, [Link]))
{
await [Link](stream);
}
}
}
// process uploaded files
// Don't rely on or trust the FileName property without
validation.
return Ok(new { count = [Link], size,
filePaths });
}
Hope you have understood the implementation of file uploading in
[Link] core
Now probably you would like to know how to retrieve and display
any uploaded file from any folder under wwwroot in [Link] core !
Retrieve static files in [Link] Core
Retrieve images from wwwroot
In earlier article i shared how to upload multiple image files in
[Link] core wwwroot folder
Now we learn how to retrieve image files from any folder under
wwwroot, display images on screen and delete image in [Link] core
web application.
Load Images in Controller [Link] Core
First we design a model with few properties, so in controller we can
fill those properties and access in razor view, in model we have a
FileInfo array type property called “Files”, we will use this property
for retrieving images from a folder under wwwroot in [Link] core
Here is how the model code will look like.
namespace [Link]
{
public class FileManagerModel
{
public FileInfo[] Files { get; set; }
public IFormFile IFormFile { get; set; }
public List<IFormFile> IFormFiles { get; set; }
}
}
We need to access the root folder of the application in our controller
code, and to do that we need use PhysicalFileProvider service.
Add Middleware Service in Startup
You need to add following Middleware Service reference in
ConfigureServices method of [Link] file. In your
ConfigureService method there may be many other services already
added, so just add IFileProvider Service also.
using [Link];
using [Link];
public void ConfigureServices(IServiceCollection services)
{
[Link]<IFileProvider>(new
PhysicalFileProvider(
[Link]([Link](),
"wwwroot")));
[Link]();
}
Get file path in [Link] Core
To get folder reference in [Link] Core Controller you need to Add
IHostingEnvironment in Controller with DI (Dependency Injection)
Now you need the folder reference where you want to save all
uploaded image files, and to get that you need an instance of
IHostingEnvironment, so in controller constructor we create the
instance using dependency injection
private readonly IHostingEnvironment _hostingEnvironment;
public fileuploadController(IHostingEnvironment
hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
Now whenever you want to access wwwroot folder in your controller,
just write _hostingEnvironment.WebRootPath
Now in controller code we fetch all images from specified folder
(“userimages” under “wwwroot”) , and set in model property (File
Array)
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
public IActionResult index()
{
FileManagerModel model = new FileManagerModel();
var userImagesPath =
[Link](_hostingEnvironment.WebRootPath,
"userimages");
DirectoryInfo dir = new DirectoryInfo(userImagesPath);
FileInfo[] files = [Link]();
[Link] = files;
return View(model);
}
Display images from wwwroot folder
Finally, we need to display all images in our [Link] core razor view;
we also have a provision to delete any image from this screen also
from file system (folder under "wwwroot")
@if ([Link] != null)
{
foreach (FileInfo f in [Link])
{
<div class="col-lg-3">
<img src="~/userimages/@[Link]"
style="width:90%;">
<div style="padding:10px;text-align:center"><a
href="@[Link]("deletefile","fileupload",new
{ fname=[Link]})">Delete</a></div>
</div>
}
}
<div class="clearfix"></div>
Please take a look at the screen below.
Delete Image from folder in [Link] core
Now as you see there is delete link under each screen in above
image, once you click the image will be deleted from folder
permanently and the screen will be reloaded without that image.
In razor view you need to just pass the unique identifier for that
image to call an action, here I am passing the image name.
<a href="@[Link]("deletefile","fileupload",new
{ fname=[Link]})">Delete</a>
Now in controller we have to write action method to receive the
delete request and finally delete that image from folder and
redirecting to a different action method.
public IActionResult deletefile(string fname)
{
string _imageToBeDeleted =
[Link](_hostingEnvironment.WebRootPath,
"userimages\\",fname);
if (([Link](_imageToBeDeleted)))
{
[Link](_imageToBeDeleted);
}
return RedirectToAction("index",new { deleted=
fname });
}
Hope you understood retrieving, displaying and deleting files from
[Link] core folder
Microservices in .Net Core
What is Microservices in .Net Core?
Microsoft has introduced a service oriented architecture that can be
containerized and independent. Microservices are type of API
service, that are small, modular, can be deployed independently,
which can run in an isolated environment.
You also can say Microservices is a type of SOA (Service Oriented
Architecture), an architectural design that separates portions of an
application into small, self-containing services, one Microservice can
have multiple services within it, but it’s designed as small as
necessary.
There is fantastic document for .NET Microservices Architecture
Guidance from Microsoft.
Microservices Characteristic
Any microservice is self independent, deployment and
consumption will not depend on anything, so if you have
multiple micro services as a part of any big enterprise
system, there are chances that you may have same data
duplicated in different micro service, as per micro service
design principal that’s not incorrect design.
So while designing any microservices we should try to
minimize the interaction between the internal microservices,
the less interaction between microservices is better, but in
some situation you may need to integrate other
microservices as per business demand, in such cases make
sure all communication are asynchronous.
Microservices Architecture
As explained earlier micro services are small independent service
that can interact with any number of services or different type of
clients, but to understand it in typical enterprise scenario where
probably we can have any number of micro services and any number
of applications, following picture is the representation of one such
scenario .
Difference between Web API and Microservices
At this point you may think what’s the difference between Web API
and Microservices, because there are many similarities.
The main conceptual difference is, Microservices is an architectural
pattern of building small independent services that can work with
multiple systems, so from business point of view, you can build
multiple Microservices rather than building a big system together.
When API is designed for providing a cross platform data
interoperability mechanism, where Microservices is much bigger
picture.
Now if you think of a big enterprise business, where business
demand is constantly changing, and there are so many
interdependency factors, so maintaining everything in one system
become tough, impact analysis takes lots of time, also there are high
risk involved. And that’s where Microservices makes the job much
easier and easy to maintain, that’s the reason Microservices
architecture is becoming so popular
How to build Microservices
Here I will explain you a simple step of building small microservice
from scratch
Select .Net Core framework and “API ” project, if your operating system
supports docker then you can enable docker otherwise ignore , (if you
are developing on windows 10 then probably you have docker support, if
using windows 7, then please ignore )
Globalization and Localization with [Link] Core
Learn how to implement Globalization and Localization in
[Link] Core application
Implement Globalization and Localization
What is Globalization?
Globalization is the process of making a globalised web application,
which means there will be different content for different geography,
means localised content.
What is Localization?
Localization is the process of setting up content for local geography,
continuation process of globalization.
[Link] core provides mechanism of adding local culture info into
middleware
using [Link];
using [Link];
IList<CultureInfo> supportedCultures = new
List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("fi-FI"),
};
[Link](new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
Localization Setup
To setup localization in controller you need to add following code.
Things to notice
Required namespace
Dependency Injection through constructor
Using the instance of IStringLocalizer
Note:
Like earlier version of [Link] we still can use resource file (.resx) to
store localization information in the form of key-value pair, but now in
[Link] core we can store localization information in Json file (.json)
too, the disadvantage of keeping information in resx file is, that every
time we add a new key, we need to compile the assembly for that key to
get reflected, on the other hand using JSON file we can add any key and
use them in razor view without compiling the whole assembly again.
Controller Setup
Here is how localization can be implemented in controller level, also
have a provision to change the current culture by user from UI
through query string
using [Link];
using [Link];
using [Link];
public class welcomeController : Controller
{
private readonly IStringLocalizer<welcomeController>
_localizer;
public
welcomeController(IStringLocalizer<welcomeController>
localizer)
{
_localizer = localizer;
}
public IActionResult index()
{
return View();
}
public IActionResult hello()
{
string currentCulture = [Link]["culture"];
if ()
{
[Link] = new
CultureInfo(currentCulture);
}
ViewData["WelcomeMessage"] =
_localizer["WelcomeMessage"];
return View();
}
}
Implement Localization Step by Step
Here is the complete localization implementation with working code
(you can straight away use the code in your project)
Step 1
Right click on your project then "Manage NuGet Packages", and then
add following two packages in your solution
[Link]
[Link]
Install NuGet package "[Link]"
Step 2
Open your [Link] file and add following code in
"ConfigureServices" method.
public void ConfigureServices(IServiceCollection services)
{
#region Localization
[Link]<IdentityLocalizationService>();
[Link](o =>
{
// We will put our translations in a folder called
Resources
[Link] = "Resources";
});
[Link]<IStringLocalizerFactory,
JsonStringLocalizerFactory>();
[Link]<IStringLocalizer,
JsonStringLocalizer>();
[Link]()
.AddViewLocalization(LanguageViewLocationExpanderFo
[Link],
opts => { [Link] = "Resources"; })
.AddDataAnnotationsLocalization(options =>
{
});
[Link] = new CultureInfo("en-US");
#endregion
}
Notice how default culture has been set
using [Link]
Now add the following code in "Configure" method of same
[Link] file
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
#region Localization
IList<CultureInfo> supportedCultures = new
List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("en-IN"),
new CultureInfo("fr-FR"),
};
var localizationOptions = new
RequestLocalizationOptions
{
DefaultRequestCulture = new
RequestCulture(culture: "en-US", uiCulture: "en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
};
[Link](localizationOptions);
var requestProvider = new
RouteDataRequestCultureProvider();
[Link](0,
requestProvider);
var locOptions =
[Link]<IOptions<RequestLocaliza
tionOptions>>();
[Link]([Link]);
#endregion
}
Step 3
You need to write following custom classes for localization in Json
format. Let's create a class with name "JsonLocalization"
using [Link];
using [Link];
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace WebTrainingRoom
{
class JsonLocalization
{
public string Key { get; set; }
public Dictionary<string, string> LocalizedValue =
new Dictionary<string, string>();
}
public class JsonStringLocalizerFactory :
IStringLocalizerFactory
{
public IStringLocalizer Create(Type resourceSource)
{
return new JsonStringLocalizer();
}
public IStringLocalizer Create(string baseName,
string location)
{
return new JsonStringLocalizer();
}
}
public class JsonStringLocalizer : IStringLocalizer
{
List<JsonLocalization> localization = new
List<JsonLocalization>();
public JsonStringLocalizer()
{
//read all json file
JsonSerializer serializer = new
JsonSerializer();
localization =
[Link]<List<JsonLocalization>>(File.
ReadAllText(@"Resources/[Link]"));
}
public LocalizedString this[string name]
{
get
{
var value = GetString(name);
return new LocalizedString(name, value ??
name, resourceNotFound: value == null);
}
}
public LocalizedString this[string name, params
object[] arguments]
{
get
{
var format = GetString(name);
var value = [Link](format ?? name,
arguments);
return new LocalizedString(name, value,
resourceNotFound: format == null);
}
}
public IEnumerable<LocalizedString>
GetAllStrings(bool includeParentCultures)
{
return [Link](l =>
[Link](lv => lv ==
[Link])).Select(l => new
LocalizedString([Link],
[Link][[Link]], true));
}
public IStringLocalizer WithCulture(CultureInfo
culture)
{
return new JsonStringLocalizer();
}
private string GetString(string name)
{
var query = [Link](l =>
[Link](lv => lv ==
[Link]));
var value = [Link](l => [Link] ==
name);
return
[Link][[Link]];
}
}
}
Notice in above code, we have specified the json file location
at [Link](@"Resources/[Link]") . Means in
root of the application there is a folder called “Resources” , then
there is a file called "[Link]"
Step 4
Now create a class with name “IdentityLocalizationService”. Now
create a class with name “IdentityLocalizationService”, in this class
we have methods that will allow us to access localized string based
on key
using [Link];
using [Link];
namespace [Link]
{
public class IdentityLocalizationService
{
private readonly IStringLocalizer _localizer;
public
IdentityLocalizationService(IStringLocalizerFactory
factory)
{
var type = typeof(IdentityResource);
var assemblyName = new
AssemblyName([Link]().[Link]);
_localizer = [Link]("IdentityResource",
[Link]);
}
public LocalizedString
GetLocalizedHtmlString(string key)
{
return _localizer[key];
}
public LocalizedString
GetLocalizedHtmlString(string key, string parameter)
{
return _localizer[key, parameter];
}
}
public class IdentityResource
{
}
Step 5
If you want multiple-localization to be implemented, then you need
to add multiple json file with same key values.
[Link]
{
"WelcomeMessage": "Welcome to my World."
}
[Link]
{
"WelcomeMessage": "Namaskar! Apne Ghar Ayyea"
}
You also can write all in one json file
[
{
"Key": "WelcomeMessage",
"LocalizedValue" : {
"fr-FR": "Bienvenue dans mon monde.",
"en-US": "Welcome to my Home.",
"en-IN": "Swagatam! Apne Ghar Ayyea."
}
}
]
How to change current culture
You may need to provide an option of changing current culture to
your web page visitor, so in case they want to change the current
culture, they can easily switch to their native culture
[Link] = new CultureInfo("en-IN");
string currentCulture = [Link]["culture"];
if ()
[Link] = new
CultureInfo(currentCulture);
How to get the list of all CultureInfo
Here are few lines of code can get you the list of all culture info, so
you can set the right culture for your required geography, remember
you need to use the right culture name; otherwise it may get you
error.
using System;
using [Link];
using [Link];
List<string> list = new List<string>();
foreach (CultureInfo ci in
[Link]([Link]))
{
[Link]([Link]("{0} / {1}", [Link],
[Link]));
}
[Link](); // sort by name