Developers use the .Net development tools for building amazing software and websites for their business. This proves that the utilization of developer tools is

seen from United States
seen from United States
seen from United Kingdom

seen from Maldives
seen from Russia
seen from Malaysia

seen from Argentina

seen from Australia

seen from United Kingdom
seen from United States

seen from Malaysia

seen from Argentina
seen from Serbia

seen from Poland
seen from Belgium

seen from United States
seen from United States
seen from Netherlands

seen from Singapore

seen from United Kingdom
Developers use the .Net development tools for building amazing software and websites for their business. This proves that the utilization of developer tools is
Learn how to create and deploy a SPA in C# with Blazor. This book is a comprehensive guide about the new modern Blazor framework. It explains how you can start the development process, what tools you can use to develop an application, and how you can deploy it. Blazor [Book]: Web App with Blazor and ASP .Net Core | Blazor Ebook Download
Key Features
Get familiar with the basic and advanced concepts of the Blazor framework
Understand how to implement JavaScript interop in Blazor
Learn how to inject the service dependency in Blazor
Learn how to implement security using Authentication and authorization
Deploy and host your Blazor app on IIS and Azure
Asp.Net Razor Pages By Sagar Jaybhay
New Post has been published on https://is.gd/dlFzRM
Asp.Net Razor Pages By Sagar Jaybhay
In article we will understand Asp.Net Razor Pages By Sagar Jaybhay.
Asp.Net MVC we have 3 different components Controller, Model, and View. In Asp.Net razor pages we have only two components 1) Display template and 2) Page Model Class.
Page model class has OnGet and OnPost methods. Which are worked as the Controllers’ action method in MVC?
The properties which you write in Page Model class are available in the Display template file of that class.
When you create Razor application you can see Index and Privacy are default files are added. In Index model class we added Message Property and assign value to that message property in OnGet method. To use this property in our Display template which is our view Index.cshtml file. In that file, we need to @(at the rate) symbol before model and by using(dot). you can assess these properties.
using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace RazorApplication.Pages public class IndexModel : PageModel private readonly ILogger<IndexModel> _logger; public string Message get; set; public IndexModel(ILogger<IndexModel> logger) _logger = logger; public void OnGet() Message = "Hello Mr. Sagar Jaybhay.";
Our application we have View which is Display template and code for that is shown below.
@page @model IndexModel @ ViewData["Title"] = "Home page"; <div class="text-center"> <h1 class="display-4">@Model.Message</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div>
So it means that Code behind file of our View i.e Index.cshtml file is View and its code behind is Index.cshtml.cs file which worked as model. Means you can define as many as file in this. The methods in that model i.e OnGet() and OnPost() handles get and post methods. Which ultimately means that PageModel class which worked as Model and Controller and Display template works as view in Asp.Net MVC.
Razor Pages are a new technology that is for building a website is fast and you can think as Razor pages work as Classic Asp.Net webforms framework.
Whatever we put in PageModel class is related to that page only.
Layout View In Asp.Net Razor
The common section in a web application presents means header, footer, left menu and right-menu like that. For this, in our Asp.Net MVC, we have a Layout view. If you want to find a page in View or Page then go to the first line of View code and if you find @Page directive it means that it is Page. In our Layout.cshtml file we don’t have @Page directive means it in Layout View.
In the Asp.Net razor, pages project not processing static files directly and not gives as output for this purpose we need to add StaticFile middler-ware in startup class file in configure method.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); else app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => endpoints.MapRazorPages(); );
@asp-page anchor tag helper
This asp-page is an anchor tag helper and it sets the href attribute for the anchor tag.
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
@asp-append-version anchor tag helper
This tag helper is used to caching a busting mechanism for static files. It is mainly used for images, javascript files.
@RenderBody anchor tag helper
This is a tag helper is used to render a page at that location. It Means that , if you declared this tag inside div then Pages like Index.cshtml, Privacy.cshtml are included or rendered inside that div element and plugin their content at this location where we include this @RenderBody() tag.
@RenderSection anchor tag helper
It is used to render the content in a separate place.
@RenderSection("footer", required: false) @section Footer <p>Section/Index page</p>
We can designate content to be rendered at RenderSection using a @section declaration. This allows us to again separate layout from content and provides a flexible framework to build our views.
Note the required: false call in RenderSection. By default, Sections are required, meaning each child view must define the section. We pass required: false to designate that the section is optional.
Below is tag helper in detail URL:- https://sagarjaybhay.com/tag-helpers-in-asp-net-core-mvc-sagar-jaybhay/
GitHub Link:- https://github.com/Sagar-Jaybhay/AspNetRazor
How to delete Identity User in Asp.net core ? 2019
New Post has been published on https://is.gd/SkQZmt
How to delete Identity User in Asp.net core ? 2019
(adsbygoogle = window.adsbygoogle || []).push();
Create Identity User: https://sagarjaybhay.com/identity-in-aspnet-core-part-1-sagar-jaybhay/
To delete identity users from a database we need to use a Post request call. This can be done using get call also but it is not recommended.
(adsbygoogle = window.adsbygoogle || []).push();
List Identity users in asp.net core
In the previous article, we have created ListOfUsers functionality where we added Edit User and Delete User buttons to a list of users. On delete button click we called DeleteUser method in our RoleManage Controller and it is a post method.
For button click which is post-call, we create a form tag where we add button and whose type is submitted and for action call, we give asp-action and asp-controller values respectively. Below is code snippet for this
<div class="card-footer"> <div class="row col-12"> <a class="btn btn-primary " asp-route-id="@users.Id" asp-controller="Rolemanag" asp-action="EditUser"> Edit </a> <div class="col-1"></div> <form method="post" asp-action="DeleteUser" asp-controller="Rolemanag" asp-route-UserID="@users.Id"> <button type="submit" class="btn btn-danger " value="Delete">Delete</button> </form> </div>
In this pass asp-route-UserId for identifying the user by using userid using UserManager service which is injected in our controller.
[HttpPost] public async Task<IActionResult> DeleteUser(string UserID) var user =await _userManager.FindByIdAsync(UserID); if (user != null) var result = await _userManager.DeleteAsync(user); if (result.Succeeded) return RedirectToAction("ListOfRoles"); foreach (var error in result.Errors) ModelState.AddModelError("",error.Description); else return View("NotFound"); return View("NotFound");
In this method we first find a user by id if this user is found then we can delete else we return the result, NotFound Page.
Now this regular code, but if we have to delete something we need to add user confirmation for that. So there are 2 ways we can user confirmation for delete identity users in asp .net core.
First Approach:
In this approach, we have created an alert confirmation box. In this, we have a javascript function we added which returns a response that is true or false. And this is return response to form and if our response is true then our post method is called else it is not called.
Below is the code for onclick.
<form method="post" asp-action="DeleteUser" asp-controller="Rolemanag" asp-route-UserID="@users.Id"> <button type="submit" class="btn btn-danger " value="Delete" onclick="return confirm('Are you sure,for delete this user :@users.UserName')">Delete</button> </form>
onclick in identity user in asp.net core
delete identity user in asp.net core
Second Approach To Delete Identity User
In this approach, we have created InLine alert because as in the previous approach we create alert but always it is not a good way to show the alert.
Inline Message Delete In Asp.Net Core
To achieve this functionality we have created one span and in that span element, we added text and two buttons which is for yes and No like below.
<form method="post" asp-action="DeleteUser" asp-controller="Rolemanag" asp-route-UserID="@users.Id"> <span style="display: none" id="[email protected]"> <span>Are you sure,for delete this user.</span> <button type="submit" class="btn btn-danger" >Yes</button> <a href="#" class="btn btn-primary" onclick="DeleteUser('@users.Id',false)">No</a> </span> <a href="#" class="btn btn-danger" value="Delete" onclick="DeleteUser('@users.Id',true)" id="DeleteButton">Delete</a> </form>
After this, In the above code, we have a delete button, when you click that delete button in-line message show and when you click on yes it will call our delete method in controller else for no button it reset the UI. Also for toggle view functionality, we created on a javascript function whose code like below
<script> function DeleteUser(UserID,isDeleted) var ID = "DeleteSpan_" + UserID; if (!isDeleted) document.getElementById('DeleteButton').style.display = "block"; document.getElementById(ID).style.display = "none"; else document.getElementById('DeleteButton').style.display = "none"; document.getElementById(ID).style.display = "block"; </script>
Inline Mesasge asp.net core part 2
GitHub Project Link: https://github.com/Sagar-Jaybhay/LearnAspNetCore
How to edit user information in asp.net core vs 2.1?
New Post has been published on https://is.gd/6KLDI6
How to edit user information in asp.net core vs 2.1?
(adsbygoogle = window.adsbygoogle || []).push();
Article : https://sagarjaybhay.com/how-to-register-new-user-using-asp-net-core-identity/
Edit User Information In Asp.Net Core
For every edit operation or update operation, it is good practice to create a view model for that information class. As we are editing users class we can create here EditUserViewModel Class and added some properties which are shown below.
(adsbygoogle = window.adsbygoogle || []).push();
public class EditUserViewModel public string Id get; set; [Required] public string UserName get; set; [Required] [EmailAddress] public string Email get; set; public string City get; set; public List<string> Claims get; set; =new List<string>(); public List<string> Roles get; set; =new List<string>();
For edit user we create one method which is EditUser action method in our RoleManagController and In this method we pass User Id from edit button click event from our list of users view.
By using this Id we can find user by using UserManager service which is injected in our controller. The code of this method shown below.
[HttpGet] public async Task<IActionResult> EditUser(string Id) var user = await _userManager.FindByIdAsync(Id); if (user == null) ViewBag.ErrorMessage = $"UserID :Id of this customer is not found."; return View("NotFound"); var userClaims = await _userManager.GetClaimsAsync(user); var userRoles = await _userManager.GetRolesAsync(user); var model=new EditUserViewModel() Id = Id, City = user.City, UserName = user.UserName, Email = user.Email, Claims = userClaims.Select(c=>c.Value).ToList(), Roles = userRoles.ToList() ; return View(model);
In this, we first check the user is valid or present or not. If the user presents then by using a usermanager service object we can get access to the claims which are in-built methods provided in asp.net core similarly we can get roles from Users by using the in-built method GetRolesAsync method and we can set the properties of our EditUserViewModel class.
Then we pass this Viewmodel class object to our view and we show edit user information form. For this view, we can use an in-built edit form property to create a view.
Edit view Code is below
@model LearnAspCore.ViewModel.EditUserViewModel @ ViewData["Title"] = "EditUser"; <h1>EditUser</h1> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="EditUser"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Id" class="control-label"></label> <input asp-for="Id" class="form-control" disabled="disabled" /> <span asp-validation-for="Id" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="UserName" class="control-label"></label> <input asp-for="UserName" class="form-control" /> <span asp-validation-for="UserName" 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="City" class="control-label"></label> <input asp-for="City" class="form-control" /> <span asp-validation-for="City" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Save" class="btn btn-primary" /> </div> </form> </div> </div> <hr /> <hr /> <div class="card"> <div class="card-header"> <h2>User Roles</h2> </div> <div class="card-body"> @if (Model.Roles.Any()) foreach (var role in Model.Roles) <h3 class="card-title">@role</h3> else <h1 class="text-danger">No Roles Present Currently For this User.</h1> </div> <div class="card-footer"> <a href="#" class="btn btn-primary">Manage Roles</a> </div> </div> <hr /> <hr /> <div class="card"> <div class="card-header"> <h2>User Claims</h2> </div> <div class="card-body"> @if (Model.Claims.Any()) foreach (var claim in Model.Claims) <h3 class="card-title">@claim</h3> else <h1 class="text-danger">No Claim Present Currently For this User.</h1> </div> <div class="card-footer"> <a href="#" class="btn btn-primary">Manage Claims</a> </div> </div> <div> <a asp-action="Index" asp-controller="Home">Back to List</a> </div>
Edit User In Asp.Net Core
Now we want to store this edited information into our database for that we create another method with the same name EditUser but the attribute of that method is HttpPost why? Because we created the in our edit view we use to form and the action method of this form is EditUser.
Edit User Post Action in Asp.Net Core
The code for update user information to the database is below
[HttpPost] public async Task<IActionResult> EditUser(EditUserViewModel userView) var user = await _userManager.FindByIdAsync(userView.Id); if (user == null) ViewBag.ErrorMessage = $"UserID :userView.Id of this customer is not found."; return View("NotFound"); else user.Email = userView.Email; user.City = userView.City; user.Email = userView.Email; var result = await _userManager.UpdateAsync(user); if (result.Succeeded) return RedirectToAction("ListOfUsers"); foreach (var error in result.Errors) ModelState.AddModelError("",error.Description); return View(userView);
In the above code first, we check whether the user is valid or not. If he is a valid user then we assign our EditUserViewModel properties to our existing user which is updated properties and after that, we use the UpdateAsync method of UserManager class and this is in-built service and we are injected in our controller.
After update button click if information is updated successfully we redirect the user to List of Users page. Complete code of controller is below.
using System; using System.Collections.Generic; using System.Linq; using LearnAspCore.ViewModel; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; using LearnAspCore.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity.UI.V3.Pages.Internal.Account; namespace LearnAspCore.Controllers [Authorize(Roles = "Admin")] public class RolemanagController : Controller private readonly UserManager<ExtendedIdentityUser> _userManager; public RoleManager<IdentityRole> rolesManager get; set; public RolemanagController(RoleManager<IdentityRole> rolesManager,UserManager<ExtendedIdentityUser> userManager) _userManager = userManager; this.rolesManager = rolesManager; [HttpGet] public IActionResult CreateRoles() return View(); [HttpPost] public async Task<IActionResult> CreateRoles(RoleViewModel roleView) if (ModelState.IsValid) IdentityRole role=new IdentityRole() Name = roleView.RoleName ; IdentityResult result=await this.rolesManager.CreateAsync(role); if (result.Succeeded) return RedirectToAction("ListOfRoles", "Rolemanag"); foreach (var identityErrorLE in result.Errors) ModelState.AddModelError("",identityErrorLE.Description); return View(roleView); public IActionResult ListOfRoles() var list = this.rolesManager.Roles; return View(list); [HttpGet] public async Task<IActionResult> EditRole(string id) var role =await this.rolesManager.FindByIdAsync(id); if (role == null) ViewBag.ErrorMessages = $"Role of given id id is not found."; return View("NotFound"); else var model=new EditRoleViewModel() RoleName = role.Name, Id =(role.Id), ; foreach (var users in _userManager.Users) // model.Users=new List<string>(); if (await _userManager.IsInRoleAsync(users, role.Name)) model.Users.Add(users.UserName); return View(model); [HttpPost] public async Task<IActionResult> EditRole(EditRoleViewModel model) var role = await this.rolesManager.FindByIdAsync(model.Id); if (role == null) ViewBag.ErrorMessages = $"Role of given id model.Id is not found."; return View("NotFound"); else role.Name = model.RoleName; var res=await this.rolesManager.UpdateAsync(role); if (res.Succeeded) return RedirectToAction("ListOfRoles", "Rolemanag"); foreach (var erros in res.Errors) ModelState.AddModelError("",erros.Description); return View(model); [HttpGet] public async Task<IActionResult> EditUsersInRoles(string RoleId) ViewBag.RoleId = RoleId; var role = await rolesManager.FindByIdAsync(RoleId); if (role == null) ViewBag.Message = $"Role of RoleId of this Id is Not found"; return View("NotFound"); else var model = new List<UserRoleViewModel>(); foreach (var users in _userManager.Users) var Users = new UserRoleViewModel() UserName = users.UserName, UserId = users.Id ; if (await _userManager.IsInRoleAsync(users, role.Name)) Users.IsSelected = true; else Users.IsSelected = false; model.Add(Users); return View(model); [HttpPost] public async Task<IActionResult> EditUsersInRoles(List<UserRoleViewModel> model, string RoleId) var role = await rolesManager.FindByIdAsync(RoleId); if (role == null) ViewBag.ErrorMessage = $"Role with Id=RoleId not found"; return View("NotFound"); else for (int i = 0; i < model.Count; i++) var user=await _userManager.FindByIdAsync(model[i].UserId); IdentityResult result = null; if (model[i].IsSelected == true&&!(await _userManager.IsInRoleAsync(user,role.Name))) result= await _userManager.AddToRoleAsync(user, role.Name); else if(!model[i].IsSelected&&await _userManager.IsInRoleAsync(user,role.Name)) result = await _userManager.RemoveFromRoleAsync(user, role.Name); else continue; if (result.Succeeded) if(i<(model.Count-1)) continue; else return RedirectToAction("EditRole", new Id = RoleId); return View("NotFound"); [HttpGet] [AllowAnonymous] public IActionResult AccessDenied() return View(); [HttpGet] public IActionResult ListOfUsers() var users = _userManager.Users; return View(users); [HttpGet] public async Task<IActionResult> EditUser(string Id) var user = await _userManager.FindByIdAsync(Id); if (user == null) ViewBag.ErrorMessage = $"UserID :Id of this customer is not found."; return View("NotFound"); var userClaims = await _userManager.GetClaimsAsync(user); var userRoles = await _userManager.GetRolesAsync(user); var model=new EditUserViewModel() Id = Id, City = user.City, UserName = user.UserName, Email = user.Email, Claims = userClaims.Select(c=>c.Value).ToList(), Roles = userRoles.ToList() ; return View(model); [HttpPost] public async Task<IActionResult> EditUser(EditUserViewModel userView) var user = await _userManager.FindByIdAsync(userView.Id); if (user == null) ViewBag.ErrorMessage = $"UserID :userView.Id of this customer is not found."; return View("NotFound"); else user.Email = userView.Email; user.City = userView.City; user.Email = userView.Email; var result = await _userManager.UpdateAsync(user); if (result.Succeeded) return RedirectToAction("ListOfUsers"); foreach (var error in result.Errors) ModelState.AddModelError("",error.Description); return View(userView);
GitHub Project Link: https://github.com/Sagar-Jaybhay/LearnAspNetCore
Basic Role-based Authorization in Asp.Net Core 2019
New Post has been published on https://is.gd/9CagDG
Basic Role-based Authorization in Asp.Net Core 2019
(adsbygoogle = window.adsbygoogle || []).push();
Previous articles :- https://sagarjaybhay.com/asp-net-core/
Role-based Authorization
Authorization means that if the user has rights he will able to see things. For this we use simple Authorize attribute in this we know that when we use simple Authorize attribute like below
(adsbygoogle = window.adsbygoogle || []).push();
[HttpGet] [Authorize] public ViewResult Edit(int id) try Student st = _repository.GetStudents(id); StudentEditViewModelClass editViewModelClass=new StudentEditViewModelClass() ExistingPhotoPath = st.PhotoPath, Address = st.Address, Division = st.Division, FullName = st.FullName, Id = id ; return View(editViewModelClass); catch (Exception ex) Console.WriteLine(ex); throw;
It will only check the user is login or not which is simple.
In this, we understand Role-based authorization means what,
Suppose we have 2 users ABC and xyz and ABC have administrator rights and xyz have general rights so if you want some controller only accessed by the administrator you can do so by doing the following attribute with value.
[HttpGet] [Authorize(Roles = "Admin")] public ViewResult Edit(int id) try Student st = _repository.GetStudents(id); StudentEditViewModelClass editViewModelClass=new StudentEditViewModelClass() ExistingPhotoPath = st.PhotoPath, Address = st.Address, Division = st.Division, FullName = st.FullName, Id = id ; return View(editViewModelClass); catch (Exception ex) Console.WriteLine(ex); throw;
In above code we mark method with [Authorize(Roles = “Admin”)]
This attribute you can use with a controller in the same way. Now you can give multiple values to Authorize attribute like below [Authorize(Roles = “Admin, User”)]
This also works the same way and has access to multiple roles like admin and user.
Suppose you have created a user and which is not having any kind of role assign to it then asp redirects this user to log in when it going to access the particular method or controller another action which is marked with this attribute.
[Authorize(Roles = "Admin,User")] public class HomeController : Controller private IStudentRepository _repository; private IHostingEnvironment histingEnviroment; public ILogger loggerObject get; set; public HomeController(IStudentRepository repository,IHostingEnvironment ihostEnvironment,ILogger<HomeController> logger) this._repository = repository; this.histingEnviroment = ihostEnvironment; loggerObject = logger; //[Route("")] //[Route("~/")] //[Route("[action]")] [Authorize(Roles = "User")] public ViewResult Index() loggerObject.LogCritical("LogCritical"); loggerObject.LogDebug("LogDebug"); loggerObject.LogError("LogError"); loggerObject.LogInformation("LogInformation"); loggerObject.LogTrace("LogTrace"); loggerObject.LogWarning("LogWarning"); var v = _repository.GetAllStudent(); return View(v); // [Route("[action]")] [AllowAnonymous] public ViewResult List() var v = _repository.GetAllStudent(); return View(v);
Authorize Role In Asp.Net Core
How to hide and unhide menuItem in asp.net core based on roles?
When you want to achieve this functionality you need to use SignInManager class with IsSignedIn Method and for role-based, we need to use IsInRole method of User object like below in _Layout.cshtml file.
@if (SignInManager.IsSignedIn(User) && User.IsInRole("Admin")) <li class="nav-item"> <a asp-action="CreateRoles" asp-controller="Rolemanag" class="nav-link">Create Roles</a> </li> <li class="nav-item"> <a asp-action="ListOfRoles" asp-controller="Rolemanag" class="nav-link">Role List</a> </li>
How to add access denied call in asp.net core?
In this the controller which causing you issue or generally account controller where authentication and authorization start is the start point of application so add AccessDenied method in that controller like below.
[HttpGet] [AllowAnonymous] public IActionResult AccessDenied() return View();
Make sure that the method has AllowAnonymous attribute and should respond to get a call.
Html of this method is like below
@ ViewData["Title"] = "AccessDenied"; <h1>AccessDenied</h1> <div class="text-center"> <h1><div class="text-danger">Access Denied</div></h1> <div class="text-danger">You don't have permission to access this page.</div> <div class="img-fluid"> <img src="images/access.png"/> </div> </div>
The out put of this Method is like below
access denied in asp.net core
How to display all users from the identity database?
Create a ListOfUser action method in a controller in our RoleManagerController. Register users are stored in the asp.net core identity database in the AspNetUsers tables.
To retrieve the users from the database we need UserManager service and this service we already injected in our controller.
users in asp.net core
[HttpGet] public IActionResult ListOfUsers() var users = _userManager.Users; return View(users);
This is our method in RoleManager controller and from this, we can get the users list. Then we pass this user list to our view.
@model IEnumerable<ExtendedIdentityUser> @ ViewData["Title"] = "List Of Users"; <h1>List Of Users</h1> @if (Model.Any()) foreach (var users in Model) <div class="card"> <div class="card-header"> <div class="row"> <div class="col-2"> User ID</div> <div class="col-8"> @users.Id</div> </div> </div> <div class="card-body"> <div class="row"> <div class="col-2">Email ID</div> <div class="col-8"> @users.Email</div> </div> </div> <div class="card-footer"> <button type="submit" class="btn btn-primary"> Edit </button> <button type="submit" class="btn btn-primary"> Cancel </button> </div> </div> else <h1>No User Is Present Right Now.</h1>
By passing the user’s list to our view we get the below output.
List of users in asp.net core
In this output, we show only userid and Email Id not the rest of the information. But if we want to display this information we can get easily. See below screenshot as we pass users list to view we are able to access the properties of that class.
List of users intellisense in asp.net core
GitHub Project Link: https://github.com/Sagar-Jaybhay/LearnAspNetCore
Need to Know RoleManager Asp.Net Core 2019
New Post has been published on https://is.gd/o87W7Q
Need to Know RoleManager Asp.Net Core 2019
(adsbygoogle = window.adsbygoogle || []).push();
Previous article links :- https://sagarjaybhay.com/asp-net-core/
RoleManager In Asp.Net Core
For this, we have a RoleManager class to
(adsbygoogle = window.adsbygoogle || []).push();
Create
Read
Update
Delete
The roles and we use this conjunction with userManager class and for this, we have to pass IdentityUser object. For saving role identity created one table for it in a database which is the AspNetRoles table.
First, we create a view model for creating role and for that we create rolename field in our model.
public class RoleViewModel [Required] public string RoleName get; set;
After this, we create a view for that and in this view, we use the above-created view model.
@model RoleViewModel @ ViewData["Title"] = "CreateRoles"; <h1>CreateRoles</h1> <div class="row"> <div class="col-md-4"> <form asp-action="CreateRoles" method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="RoleName" class="control-label"></label> <input asp-for="RoleName" class="form-control" /> <span asp-validation-for="RoleName" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div> </div>
After this we have created onecontroller in that we have method for register user.
public class RegistrationVIewModel [Required] [EmailAddress] [Remote(controller:"Account",action: "IsUsedEmailID")] [CustomValidator(allowedDomain:"gmail.com",ErrorMessage = "Email Domain Must Be gmail.com")] public string Email get; set; [Required] [DataType(DataType.Password)] public string Password get; set; [Required] [DataType(DataType.Password)] [Display(Name = "Confirm Password")] [Compare("Password",ErrorMessage = "Password and Confirm Password not match.")] public string ConfirmPassword get; set; public string City get; set; public string Zip get; set;
Roles in asp.net core 2019
How to create, update, delete roles in asp.net core?
First, we have created a list of all roles present in our table which is AspNetRole.
Roles created in asp.net core
Create Role In Asp.Net Core
In this, we have created action in our controller which is CreateRole in that we have added 2 methods for CreateRole. One is httpget to get only Html and another post which is for posting the roles data to a database.
[HttpGet] public IActionResult CreateRoles() return View();
For this below is the html code for this
@model RoleViewModel @ ViewData["Title"] = "CreateRoles"; <h1>CreateRoles</h1> <div class="row"> <div class="col-md-4"> <form asp-action="CreateRoles" method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="RoleName" class="control-label"></label> <input asp-for="RoleName" class="form-control" /> <span asp-validation-for="RoleName" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div> </div>
In which we have show create role html page and page looks like below
Create Role Ui in asp.net core
For post method
[HttpPost] public async Task<IActionResult> CreateRoles(RoleViewModel roleView) if (ModelState.IsValid) IdentityRole role=new IdentityRole() Name = roleView.RoleName ; IdentityResult result=await this.rolesManager.CreateAsync(role); if (result.Succeeded) return RedirectToAction("ListOfRoles", "Rolemanag"); foreach (var identityErrorLE in result.Errors) ModelState.AddModelError("",identityErrorLE.Description); return View(roleView);
Method this is code in controller.
Display All Roles in Asp.Net Core
In our constructor, we injected RoleManager by using dependency injection below is the code for that
public RoleManager<IdentityRole> rolesManager get; set; public RolemanagController(RoleManager<IdentityRole> rolesManager,UserManager<ExtendedIdentityUser> userManager) _userManager = userManager; this.rolesManager = rolesManager;
So by using this object, we are able to get all roles present currently. For that, we have created one method in our controller below is the method.
public IActionResult ListOfRoles() var list = this.rolesManager.Roles; return View(list);
and html code for this is
@model IQueryable<IdentityRole>; @ ViewData["Title"] = "ListOfRoles"; <h1>All Roles</h1> @if (Model.Any()) foreach (var role in Model) <div class="card"> <div class="card-header"> @role.Id </div> <div class="card-body"> <h4 class="card-title"> @role.Name </h4> </div> <div class="card-footer"> <a class="btn btn-info" asp-action="EditRole" asp-controller="Rolemanag" asp-route-id="@role.Id">Edit</a> <a class="btn btn-danger" asp-action="" asp-controller="">Delete</a> </div> </div> else <div class="card"> <div class="card-header"> No Roles Found In Table </div> <div class="card-body"> <a class="btn btn-info" asp-action="CreateRoles" asp-controller="Rolemanag">Create Role</a> </div> </div>
Below is the output of that Html code
All Roles in Asp.net Core
In this, we are giving the functionality of the Edit and Delete role.
Edit Role in asp.net core
As you can see In AspNetRole table contains a name, normalized name, id and concurrency stamp. By using the edit role you can edit the name of a role. For edit role, we required ID which is auto-generated and we pass this id to our function and get a role from this.
Also for edit role, we created 2 action methods one for HttpGet and another for HttpPost and below is httpget method for EditRole which sends us Html
[HttpGet] public async Task<IActionResult> EditRole(string id) var role =await this.rolesManager.FindByIdAsync(id); if (role == null) ViewBag.ErrorMessages = $"Role of given id id is not found."; return View("NotFound"); else var model=new EditRoleViewModel() RoleName = role.Name, Id =(role.Id), ; foreach (var users in _userManager.Users) if (await _userManager.IsInRoleAsync(users, role.Name)) model.Users.Add(users.UserName); return View(model);
Which and Html for this is like below
@model EditRoleViewModel @ ViewData["Title"] = "EditRole"; <h1>Edit Role</h1> <form asp-action="EditRole" method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Id" class="control-label"></label> <input asp-for="Id" class="form-control" disabled="disabled" /> <span asp-validation-for="Id" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="RoleName" class="control-label"></label> <input asp-for="RoleName" class="form-control" /> <span asp-validation-for="RoleName" class="text-danger"></span> </div> <div class="form-group"> <button type="submit" class="btn btn-primary"> update</button> <a type="submit" value="Cancel" class="btn btn-primary" asp-action="ListOfRoles" asp-controller="Rolemanag">Cancel</a> </div> <div class="card"> <div class="card-header"> <h2 class="card-title">User Name </h2> </div> <div class="card-body"> @if (Model?.Users?.Any()!=null) foreach (var user in Model.Users) <h5>@user</h5> else <h3 class="text-danger" >No matching user found with this role</h3> </div> </div> </form>
Html for edit view we created one view model for that which is shown below
public class EditRoleViewModel public string Id get; set; [Required(ErrorMessage = "Role Name Is Required.")] public string RoleName get; set; public List<string> Users get; set;
And we use this in our view.
Edit Role in Asp.net core
In this, we pass Id as a parameter and by that id, we retrieve the role. Then if we change the name we can update this.
Update Role For Users
In identity, framework Users are stored in the AspNetUsers table
Roles are stored in AspNetRoles
We have these 2 tables i.e AspNetUsers and AspNetRoles have many to many relationships between table.
We have another table AspNetUserRoles which is inbuilt and have 2 columns only UserId and RoleId and these both columns are foreign keys of AspNetUsers nad AspNetRoles.
First, we have a list of all roles which is shown below
All Saved Roles In asp.net core
When we click on Edit role we see below result
Edit Roles New In asp.net core
For edit, role post-action below is the method when we click on the Update button.
[HttpPost] public async Task<IActionResult> EditRole(EditRoleViewModel model) var role = await this.rolesManager.FindByIdAsync(model.Id); if (role == null) ViewBag.ErrorMessages = $"Role of given id model.Id is not found."; return View("NotFound"); else role.Name = model.RoleName; var res=await this.rolesManager.UpdateAsync(role); if (res.Succeeded) return RedirectToAction("ListOfRoles", "Rolemanag"); foreach (var erros in res.Errors) ModelState.AddModelError("",erros.Description); return View(model);
And View of this is below
@model EditRoleViewModel @ ViewData["Title"] = "EditRole"; <h1>Edit Role</h1> <form asp-action="EditRole" method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Id" class="control-label"></label> <input asp-for="Id" class="form-control" disabled="disabled" /> <span asp-validation-for="Id" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="RoleName" class="control-label"></label> <input asp-for="RoleName" class="form-control" /> <span asp-validation-for="RoleName" class="text-danger"></span> </div> <div class="form-group"> <button type="submit" class="btn btn-primary"> update</button> <a type="submit" value="Cancel" class="btn btn-primary" asp-action="ListOfRoles" asp-controller="Rolemanag">Cancel</a> </div> <div class="card"> <div class="card-header"> <h2 class="card-title">User Name </h2> </div> <div class="card-body"> @if (Model?.Users?.Any() != null) foreach (var user in Model.Users) <h5>@user</h5> else <h3 class="text-danger">No matching user found with this role</h3> </div> <div class="card-footer"> <a type="submit" class="btn btn-primary" asp-action="EditUsersInRoles" asp-controller="Rolemanag" asp-route-RoleId="@Model.Id"> Add / Remove Users</a> </div> </div> </form>
Complete controller code
using System; using System.Collections.Generic; using LearnAspCore.ViewModel; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; using LearnAspCore.Models; using Microsoft.AspNetCore.Identity.UI.V3.Pages.Internal.Account; namespace LearnAspCore.Controllers public class RolemanagController : Controller private readonly UserManager<ExtendedIdentityUser> _userManager; public RoleManager<IdentityRole> rolesManager get; set; public RolemanagController(RoleManager<IdentityRole> rolesManager,UserManager<ExtendedIdentityUser> userManager) _userManager = userManager; this.rolesManager = rolesManager; [HttpGet] public IActionResult CreateRoles() return View(); [HttpPost] public async Task<IActionResult> CreateRoles(RoleViewModel roleView) if (ModelState.IsValid) IdentityRole role=new IdentityRole() Name = roleView.RoleName ; IdentityResult result=await this.rolesManager.CreateAsync(role); if (result.Succeeded) return RedirectToAction("ListOfRoles", "Rolemanag"); foreach (var identityErrorLE in result.Errors) ModelState.AddModelError("",identityErrorLE.Description); return View(roleView); public IActionResult ListOfRoles() var list = this.rolesManager.Roles; return View(list); [HttpGet] public async Task<IActionResult> EditRole(string id) var role =await this.rolesManager.FindByIdAsync(id); if (role == null) ViewBag.ErrorMessages = $"Role of given id id is not found."; return View("NotFound"); else var model=new EditRoleViewModel() RoleName = role.Name, Id =(role.Id), ; foreach (var users in _userManager.Users) // model.Users=new List<string>(); if (await _userManager.IsInRoleAsync(users, role.Name)) model.Users.Add(users.UserName); return View(model); [HttpPost] public async Task<IActionResult> EditRole(EditRoleViewModel model) var role = await this.rolesManager.FindByIdAsync(model.Id); if (role == null) ViewBag.ErrorMessages = $"Role of given id model.Id is not found."; return View("NotFound"); else role.Name = model.RoleName; var res=await this.rolesManager.UpdateAsync(role); if (res.Succeeded) return RedirectToAction("ListOfRoles", "Rolemanag"); foreach (var erros in res.Errors) ModelState.AddModelError("",erros.Description); return View(model); [HttpGet] public async Task<IActionResult> EditUsersInRoles(string RoleId) ViewBag.RoleId = RoleId; var role = await rolesManager.FindByIdAsync(RoleId); if (role == null) ViewBag.Message = $"Role of RoleId of this Id is Not found"; return View("NotFound"); else var model = new List<UserRoleViewModel>(); foreach (var users in _userManager.Users) var Users = new UserRoleViewModel() UserName = users.UserName, UserId = users.Id ; if (await _userManager.IsInRoleAsync(users, role.Name)) Users.IsSelected = true; else Users.IsSelected = false; model.Add(Users); return View(model); [HttpPost] public async Task<IActionResult> EditUsersInRoles(List<UserRoleViewModel> model, string RoleId) var role = await rolesManager.FindByIdAsync(RoleId); if (role == null) ViewBag.ErrorMessage = $"Role with Id=RoleId not found"; return View("NotFound"); else for (int i = 0; i < model.Count; i++) var user=await _userManager.FindByIdAsync(model[i].UserId); IdentityResult result = null; if (model[i].IsSelected == true&&!(await _userManager.IsInRoleAsync(user,role.Name))) result= await _userManager.AddToRoleAsync(user, role.Name); else if(!model[i].IsSelected&&await _userManager.IsInRoleAsync(user,role.Name)) result = await _userManager.RemoveFromRoleAsync(user, role.Name); else continue; if (result.Succeeded) if(i<(model.Count-1)) continue; else return RedirectToAction("EditRole", new Id = RoleId); return View("NotFound");
And for EditUsersInRoles html template is below
@model List<UserRoleViewModel> @ ViewData["Title"] = "EditUsersInRoles"; <h1>EditUsersInRoles</h1> @ var RoleID = ViewBag.RoleId; <form method="post"> <div class="card"> <div class="card-header"> <h3>Add and Remove Users For this Role</h3> </div> <div class="card-body"> @for (int i = 0; i < Model.Count; i++) <div class="form-check"> <input type="hidden" asp-for="@Model[i].UserId" /> <input type="hidden" asp-for="@Model[i].UserName" /> <input asp-for="@Model[i].IsSelected" class="form-check-input" /> <label>@Model[i].UserName</label> </div> </div> <div class="card-footer"> <input type="submit" value="Update" class="btn btn-primary" /> <a type="submit" class="btn btn-primary" asp-action="EditUsersInRoles" asp-controller="Rolemanag" asp-route-RoleId="@RoleID">Cancel</a> </div> </div> </form>
Now when we click on add and remove user roles below is output
Edit The Users In Roles
GitHub Project Link: https://github.com/Sagar-Jaybhay/LearnAspNetCore
Custom Validation Attribute Asp.Net Core 2019
New Post has been published on https://is.gd/GGnVSn
Custom Validation Attribute Asp.Net Core 2019
(adsbygoogle = window.adsbygoogle || []).push();
Complete Asp.Net Core Tutorial Step By Step :-https://sagarjaybhay.com/asp-net-core/
How to Create Custom Validation Attrbute Asp.Net Core?
Built-in Validation Attribute
(adsbygoogle = window.adsbygoogle || []).push();
Required
Range
StringLength
RegularExpression
Compare
Etc..
When in your project we have some requirements that can not be full fill with some in-built validation attributes then we need to create some Custom validation attribute. In this, we have created one CustomValidator class which inherits from ValidationAttribute inbuilt class. After inheriting from this we need to override the IsValid method.
Now in our example, we have to achieve the functionality of we are valid for only Gmail domain mail-id. Other than Gmail we restrict the user for creating an account.
After creating this CustomValidator attribute you can use this as our normal attributes.
Custom Validation Attribute Class in Asp.net core
Now we are adding code for this validation
public class CustomValidator:ValidationAttribute private string allowedDomain get; set; public CustomValidator(string allowedDomain) this.allowedDomain = allowedDomain; public override bool IsValid(object value) string[] array = value.ToString().Split("@"); if (array.Length > 1) return array[1].ToLower() == allowedDomain.ToLower(); else return false;
In this code, we have created one property allowed domain which is for we pass the domain name from our CustomValidator as a parameter.
See below code
public class RegistrationVIewModel [Required] [EmailAddress] [Remote(controller:"Account",action: "IsUsedEmailID")] [CustomValidator(allowedDomain:"gmail.com", ErrorMessage = "Email Domain Must Be gmail.com")] public string Email get; set; [Required] [DataType(DataType.Password)] public string Password get; set; [Required] [DataType(DataType.Password)] [Display(Name = "Confirm Password")] [Compare("Password",ErrorMessage = "Password and Confirm Password not match.")] public string ConfirmPassword get; set;
Now see the image
Custom Validation Attribute Declaration in asp.net core
Here we pass that parameter for that reason we need to create property and constructor in this class and need to catch this.
In this we have split the email id with the use of @ symbol then we check first array length greater than 1 and then we check with email id domain name.
See the below output
Output Of Custom Validation Attribute
GitHub Project Link: https://github.com/Sagar-Jaybhay/LearnAspNetCore