Blazor Role Management Add Role trough UI (Crud) - c#

I'm pretty new to blazor and have gotten myself in some doubt on adding roles to the database.
I have implemented to Identity role management and have a working system.
But now i want to add new roles trough the GUI instead of editing the database.
I have a razor page called RolesOverview.razor
On this page i have a input field and a button.
When i click this button i want to add the text to the roles manager and save it to the database.
This is my razor component
#page "/admin/roles"
#using Microsoft.AspNetCore.Identity
#inject RoleManager<IdentityRole> roleManager
<div class="jumbotron">
<!-- Roles Overview Group Box -->
<div class="row mb-5">
<div class="col-12">
<h1 class="display-6">Roles Options</h1>
<hr class="my-4" />
<div class="row" style="background-color:white; margin-bottom:10px; margin-top:10px;">
<div class="col-12">
<div class="card w-100 mb-3" style="min-width:100%;">
<div class="card-body">
<h5 class="card-title">Roles</h5>
<p class="card-text">
<div class="row">
<div class="col-1">
Role Name:
</div>
<div class="col-10">
<input type="text" style="min-width:100%;" placeholder="Role Type" />
</div>
<div class="col-1">
Add Role
</div>
</div>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Not Getting Saved...
#code {
private string CurrentValue { get; set; }
private async void AddRole()
{
if (CurrentValue != string.Empty)
{
if (!await roleManager.RoleExistsAsync(CurrentValue))
{
await roleManager.CreateAsync(new IdentityRole
{
Name = CurrentValue
});
}
}
}
}
I have no clue on what todo next.
I's it posible todo it with razor component or do i need to do it trough razor page?
Example would be perfect.
Regards Me!

Answer :
<div class="col-10">
<input value="#CurrentValue" #onchange="#((ChangeEventArgs __e) => CurrentValue =__e.Value.ToString())" />
#*<input type="text" style="min-width:100%;" placeholder="Role Type" />*#
</div>
<div class="col-1">
<a #onclick="AddRole" class="btn btn-primary" style="min-width:90px;">Add Role</a>
</div>
#code {
private string CurrentValue { get; set; }
private async void AddRole()
{
if (CurrentValue != string.Empty)
{
if (!await roleManager.RoleExistsAsync(CurrentValue))
{
await roleManager.CreateAsync(new IdentityRole
{
Name = CurrentValue
});
}
}
}
}

You can use RoleManager to create a new role by using the CreateAsync method:
if (!await roleMgr.RoleExistsAsync("RoleName"))
{
await roleManager.CreateAsync(new IdentityRole
{
Name = "RoleName"
});
}

Related

Data not being passed from Razor page

I have a Blazor app that takes user input via a form field and puts it into a database.
However, the data is not being passed from the front end correctly:
Razor file
#using Blogs.Shared.Models
#page "/addpost"
#inject HttpClient Http
#inject NavigationManager NavigationManager
<h2>Create Post</h2>
<hr />
<div class="row">
<div class="col-md-4">
<form>
<div class="form-group">
<label for="Name" class="control-label">Titles</label>
<input for="Name" class="form-control" bind="#posts.title" />
</div>
<div class="form-group">
<label for="Address" class="control-label">Content</label>
<input for="Address" class="form-control" bind="#posts.content" />
</div>
<div class="form-group">
<input type="button" class="btn btn-default" onclick="#(async () => await tas())" value="Save" />
<input type="button" class="btn" onclick="#Cancel" value="Cancel" />
</div>
</form>
</div>
</div>
#functions {
public Posts posts = new();
protected async Task tas()
{
await Http.PostAsJsonAsync("api/Posts/Create", posts);
NavigationManager.NavigateTo("/listposts");
}
void Cancel()
{
NavigationManager.NavigateTo("/listposts");
}
}
What I would expect this to do, is when Save is pressed, the data from Title and Content is assigned to posts and then passed to my POST method:
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Blogs.Shared.Models;
using Microsoft.AspNetCore.Mvc;
namespace Blogs.Server.Controllers
{
public class PostsController : Controller
{
private readonly IDataAccessProvider _dataAccessProvider;
private readonly ILogger _logger;
public PostsController(IDataAccessProvider dataAccessProvider, ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger("PostsController");
_dataAccessProvider = dataAccessProvider;
}
[HttpPost]
[Route("api/Posts/Create")]
public void Create(Posts post)
{
_logger.LogCritical("Data 1", post);
_logger.LogCritical("Data 2", post.content);
_logger.LogCritical("Data 3", post.title);
_dataAccessProvider.AddPosts(post);
}
}
}
All of my _logger.LogCritical lines just return blank, and when the write to the DB occurs it complains that title is empty (this field in my DB is set to NOT NULL).
Can anyone help as to why this is not working?
EDIT
I have updated the code to better match Antoine B's suggestions but its still not working:
#page "/newpost"
#using Blogs.Shared.Models
#inject HttpClient Http
#inject NavigationManager NavigationManager
<h1>#Title Post</h1>
<hr />
<EditForm Model="#posts" OnValidSubmit="SaveUser">
<DataAnnotationsValidator />
<div class="mb-3">
<label for="Name" class="form-label">Title</label>
<div class="col-md-4">
<InputText class="form-control" #bind-Value="posts.title" />
</div>
<ValidationMessage For="#(() => posts.title)" />
</div>
<div class="mb-3">
<label for="Address" class="form-label">Content</label>
<div class="col-md-4">
<InputText class="form-control" #bind-Value="posts.content" />
</div>
<ValidationMessage For="#(() => posts.content)" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Save</button>
<button class="btn btn-light" #onclick="Cancel">Cancel</button>
</div>
</EditForm>
#code {
protected string Title = "Add";
protected Posts posts = new();
protected async Task SaveUser()
{
await Http.PostAsJsonAsync("api/Posts/Create", posts);
Cancel();
}
public void Cancel()
{
NavigationManager.NavigateTo("/listposts");
}
}
To bind a value to an input component you must add an # before the bind property, like following #bind="posts.title" (see https://learn.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-6.0)
That's what's not working for you.
I also don't recommend you to use the #functions because it is not recommended by Microsoft for razor files (see https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-3.0#functions)
#code {
public Posts posts = new();
protected async Task tas()
{
await Http.PostAsJsonAsync("api/Posts/Create", posts);
NavigationManager.NavigateTo("/listposts");
}
void Cancel()
{
NavigationManager.NavigateTo("/listposts");
}
}
I hope it helped you

How to show log in pages if not authenticated?

I am using ASP.NET Core 5 Blazor server-side. Assume port was 5011, as you know, log in page is
https://localhost:5011/Identity/Account/Login
When run app, or press F5 for debugging, entry point is
https://localhost:5011
For checking authentication in web-app, I use something like these
File MainLayout.razor
#inherits LayoutComponentBase
#implements IDisposable
#inject Microsoft.AspNetCore.Components.NavigationManager NavigationManager
#inject IJSRuntime JSRuntime
#using Microsoft.JSInterop;
<AuthorizeView>
<Authorized>
<div class="sidebar">
<div class="top-row logo-container pl-4 navbar-dark bg-light text-body">
<button class="navbar-toggler" #onclick="#ToggleNavMenu">
<span class="navbar-toggler-icon"></span>
</button>
<span class="logo-image" />
#*<div class="#($"bg-light text-dark d-inline-block theme-settings { ThemeSwitcherShown }")">
<a class="nav-item nav-link" #onclick="#ToggleThemeSwitcherPanel" href="javascript:void(0);">
<span class="demo-theme-icon"></span>
</a>
</div>*#
</div>
<div class="#NavMenuCssClass">
<NavMenu />
</div>
</div>
<div class="main">
<div class="top-row bg-light text-body px-4" id="navbar">
<div class="logo">
<h5 class="caption">NumBooks</h5>
</div>
<div class="#($"theme-settings { ThemeSwitcherShown }")">
<a class="nav-item nav-link" #onclick="#ToggleThemeSwitcherPanel" href="javascript:void(0);">
<span class="demo-theme-icon"></span>
</a>
</div>
</div>
<div class="content px-4">
#Body
</div>
</div>
<ThemeSwitcher #bind-Shown="#ThemeSwitcherShown"></ThemeSwitcher>
</Authorized>
<NotAuthorized>
Log in
</NotAuthorized>
</AuthorizeView>
#*#if(!Context.User.Identity.IsAuthenticated)
{
Log in
}*#
#code {
string NavMenuCssClass { get; set; } = "";
void ToggleNavMenu()
{
NavMenuCssClass = string.IsNullOrEmpty(NavMenuCssClass) || NavMenuCssClass.Contains("d-none") ? "d-block d-xl-none" : "d-none d-xl-flex";
ThemeSwitcherShown = false;
}
bool themeSwitcherShown = false;
bool ThemeSwitcherShown
{
get => themeSwitcherShown;
set
{
themeSwitcherShown = value;
InvokeAsync(StateHasChanged);
}
}
void ToggleThemeSwitcherPanel()
{
ThemeSwitcherShown = !ThemeSwitcherShown;
}
string UriFragment { get; set; } = "";
void OnLocationChanged(object sender, LocationChangedEventArgs args)
{
if (!string.IsNullOrEmpty(NavMenuCssClass))
{
NavMenuCssClass = "";
InvokeAsync(StateHasChanged);
}
}
protected override void OnInitialized()
{
base.OnInitialized();
NavigationManager.LocationChanged += OnLocationChanged;
}
protected override Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
JSRuntime.InvokeAsync<string>("ScrollToTarget");
}
return base.OnAfterRenderAsync(firstRender);
}
void IDisposable.Dispose()
{
NavigationManager.LocationChanged -= OnLocationChanged;
}
}
Let's focus at these lines
<AuthorizeView>
<Authorized>
#* web-app for authenticated user(s). *#
</Authorized>
<NotAuthorized>
#* Press text link to go to log-in page. *#
Log in
</NotAuthorized>
</AuthorizeView>
Then, when web-app run, I press button Log in to go to https://localhost:5011/Identity/Account/Login if not authenticated. This solution is really not good. I want show Login page when user not authenticated, how to archive that?

RuntimeBinderException: Cannot perform runtime binding on a null reference

I'm making a create item page, and in this create item page there is a popup modal table where we can choose the type of UoM that we want. And normally when this form is submitted with all of the fields filled in, it saved the values into the database. But when the form is submitted with one or some or all of the fields not filled in, it supposed to give some error message that the fields are required. But it didn't and it shows this error.
These are my code
ItemController
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading.Tasks;
using CRMandOMS.Models;
using CRMandOMS.ViewModels;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace CRMandOMS.Controllers
{
public class ItemController : Controller
{
private readonly IItemRepository _itemRepository;
private readonly IUoMRepository _uoMRepository;
public ItemController(IItemRepository itemRepository, IUoMRepository uoMRepository)
{
_itemRepository = itemRepository;
_uoMRepository = uoMRepository;
}
// GET: /<controller>/
public ViewResult Index()
{
var model = _itemRepository.GetAll();
return View(model);
}
public ViewResult Details(Guid? id)
{
Item item = _itemRepository.GetById(id.Value);
return View(item);
}
[HttpGet]
public ViewResult Create()
{
ItemCreateViewModel itemCreateViewModel = new ItemCreateViewModel()
{
UoMs = _uoMRepository.GetAll()
};
return View(itemCreateViewModel);
}
[HttpPost]
public IActionResult Create(ItemCreateViewModel model)
{
if (ModelState.IsValid)
{
Item newItem = new Item
{
Name = model.Name,
Price = model.Price,
UoMId = model.UoMId
};
_itemRepository.Insert(newItem);
return RedirectToAction("Details", new { id = newItem.Id });
}
return View();
}
}
}
Create
#model CRMandOMS.ViewModels.ItemCreateViewModel
#{
ViewData["Title"] = "Item Create";
}
<h2>Item Create</h2>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a asp-controller="Item" asp-action="Index">Item</a></li>
<li class="breadcrumb-item active" aria-current="page">Create</li>
</ol>
</nav>
<form enctype="multipart/form-data" asp-controller="Item" asp-action="Create" method="post" class="mt-3">
<div class="form-group row">
<label asp-for="Name" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Name" class="form-control" placeholder="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Price" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Price" class="form-control" placeholder="Price" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="UoMId" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="UoMId" id="uomid" class="form-control" hidden />
<div class="input-group mb-3">
<input id="uomname" type="text" class="form-control" placeholder="UoM" aria-label="UoM" aria-describedby="button-uom" disabled>
<div class="input-group-append">
<button class="btn btn-outline-success" type="button" id="button-uom" data-toggle="modal" data-target="#uoMLookupTableModal">Select UoM</button>
</div>
</div>
<span asp-validation-for="UoMId" class="text-danger"></span>
</div>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-10">
<a asp-controller="Item" asp-action="Index" class="btn btn-light">Back</a>
<button type="submit" class="btn btn-success">Create</button>
</div>
</div>
</form>
#{
await Html.RenderPartialAsync("_UoMLookup");
}
#section scripts {
<script>
$(document).ready(function () {
var uoMTable = $("#uoMTable").DataTable({
"columnDefs": [
{
"targets": [0],
"visible": false
}
],
"order": [[1, "asc"]]
});
$('#uoMTable tbody').on('click', 'tr', function () {
if ($(this).hasClass('table-success')) {
$(this).removeClass('table-success');
}
else {
uoMTable.$('tr.table-success').removeClass('table-success');
$(this).addClass('table-success');
}
});
$("#getUoM").click(function () {
var uomdata = uoMTable.row('.table-success').data();
//alert(uomdata[0]);
$('#uomid').val(uomdata[0]);
//alert(uomdata[1]);
$('#uomname').val(uomdata[1]);
});
});
</script>
}
_UoMLookup
<div class="modal fade" id="uoMLookupTableModal" tabindex="-1" role="dialog" aria-labelledby="uoMLookupTableModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<table id="uoMTable" class="table table-striped table-bordered table-bordered nowrap" style="width:100%">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td>Description</td>
</tr>
</thead>
<tbody>
#foreach (UoM uom in Model.UoMs)
{
<tr>
<td class="uom-id">#uom.Id</td>
<td class="uom-name">#uom.Name</td>
<td>#uom.Description</td>
</tr>
}
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
<button id="getUoM" type="button" class="btn btn-success" data-dismiss="modal">Select</button>
</div>
</div>
</div>
</div>
ItemCreateViewModel
using CRMandOMS.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CRMandOMS.ViewModels
{
public class ItemCreateViewModel
{
[Required]
[MaxLength(100, ErrorMessage = "Name cannot exceed 100 characters")]
public string Name { get; set; }
[Required(ErrorMessage = "{0} is required")]
[Range(1000, 999999999)]
public int Price { get; set; }
[Required]
public Guid UoMId { get; set; }
public IEnumerable<UoM> UoMs { get; set; }
public string PhotoPath { get; set; }
}
}
In the HTTP POST Create method (ItemController) if the model is not valid (so ModelState.IsValid == false) you are not passing a model to your View. Ensure passing a valid model, as shown in the controller methods tutorial.
But when the form is submitted with one or some or all of the fields not filled in, it supposed to give some error message that the fields are required. But it didn't and it shows this error.
You do not have a reference to validation scripts, make sure you have _ValidationScriptsPartial.cshtml in Shared folder, then modify your code:
#section scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
<script>
//...
</script>
}
For the error on your page, just like other community has said, it is likely that the model state is invalid and it execute return View() without returning any data to create view.
However,your partial view does not allow the Model.UoMs to be null.
In your Create Post action, if the model contains UoMs, you could just use
return View(model)
otherwise ,assign UoMs data to model like what you have done in Create Get action, then return it to view.
You could always use a breakpoint on the Post action to debug the result.

IdentityCore Login or Register doesn't redirect back to home/index

i'm having problem with IdentityCore.
When i press the login button on the login form i do not get redirected to the index view, same with the register button.
This is how debug goes
I fill in the form correctly
I press the login button
The Login Action is called
Modelstate is valid and result succeeded
"User logged in" gets logged
RedirectToLocal(null) gets returned
Dependency injection calls
The Index action in home controller is called
Dishes gets loaded correctly
it returns View(dishes)
it stays in the login view instead of going to home/index
Login Form:
<form asp-route-returnurl="#ViewData["ReturnUrl"]" method="post">
<h4>Use a local account to log in.</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Email"></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="Password"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<div class="checkbox">
<label asp-for="RememberMe">
<input asp-for="RememberMe" />
#Html.DisplayNameFor(m => m.RememberMe)
</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Log in</button>
</div>
<div class="form-group">
<p>
<a asp-action="ForgotPassword">Forgot your password?</a>
</p>
<p>
<a asp-action="Register" asp-route-returnurl="#ViewData["ReturnUrl"]">Register as a new user?</a>
</p>
</div>
</form>
Login Action:
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
HomeController:
public class HomeController : Controller
{
private ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Index()
{
var dishes = _context.Dishes
.Include(d => d.IngredientDish)
.ThenInclude(id => id.Ingredient)
.Include(d => d.Category)
.ToList();
return View(dishes);
}
}
If you need more codesnippets or information do let me know

Return Partial View Via Controller Method

I have a Search Partial View that I want to return but I want to return it by running it through an exisiting Partial View Result in the Controller instead of loading the view directly.
So, in the controller I have:
public ActionResult Index()
{
return View();
}
public PartialViewResult _GetSearch(List<Search> model)
{
return PartialView("_Search", model);
}
[ValidateAntiForgeryToken()]
public PartialViewResult _BeginSearch(string search)
{
var results = SearchModels(search).ToList();
return PartialView("_GetSearch", results);
}
And in the search view itself I have:
<div class="col-md-4">
<div id="modelSearch" class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-search"></i> Search by Model / Manufacturer</h3>
</div>
<div class="panel-body">
#using (Ajax.BeginForm("_BeginSearch", "Home", new AjaxOptions() { UpdateTargetId = "modelSearch" }))
{
#Html.AntiForgeryToken()
<div class="input-group">
#Html.TextBox("search", null, new {id = "name", #class = "form-control", placeholder = "Please enter a manufacturer or model"})
<span class="input-group-btn">
<button id="search" class="btn btn-default" type="submit"><i class="fa fa-search"></i></button>
</span>
</div>
if (Model != null)
{
<div class="searchResults fade">
#foreach (var s in Model)
{
<div class="result">
#switch (s.ResultType)
{
case "Man":
#s.Manufacturer
break;
case "Mod":
#s.Manufacturer #s.Model
<img src="~/Images/General/(#s.TierId).png" alt="Tier #s.TierId"/>
break;
}
</div>
}
</div>
}
}
</div>
</div>
</div>
When I try and run the code it tell me that it cannot find the _GetSearch view, which yes technically is right, but I'm not looking for a view I'm looking for a method in the controller.

Categories

Resources