why not display text Required in Html after submit radio button empty? - asp.net

1.It delivers when you press the answer in the first question why ?
2.not display text Required in Html after submit radio button empty in span tag.
<span asp-validation-for="#item.CheckAns" class="text-danger"></span>
views/Homecontroller1/Index
This is CSHTML
#model List<QuestionCommentViewModel>
#{
ViewData["Title"] = "Index";
}
<div class="container">
<div class="row">
<div class="col-lg-12">
<form asp-action="Index" method="post">
#foreach (var item in Model)
{
<h3>#item.OneQuestions.TextQ</h3>
#foreach (var r in item.ListChoices)
{
<input type="radio" id="#r.Id" name="#r.Qid" asp-for="#item.CheckAns" value="#r.TextCh">
<label for="#r.Id">#r.TextCh</label><br>
<span asp-validation-for="#item.CheckAns" class="text-danger"></span>
}
}
<input type="submit" value="submit" style="background-color:dodgerblue;Color:white; border-radius:5px; font-weight:bold;" />
</form>
</div>
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
model
using System.Threading.Tasks;
using Task222SchoolApp.Models;
namespace Task222SchoolApp.Models
{
public class QuestionCommentViewModel
{
public Question OneQuestions { get; set; }
public IQueryable<Choice> ListChoices { get; set; }
[BindProperty, Required(ErrorMessage = "Please choose Answer.")]
public virtual string CheckAns { get; set; }
}
}
controller
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Task222SchoolApp.Models;
namespace WebApplication6.Controllers
{
public class HomeController1 : Controller
{
private readonly SchoolContext _context;
public HomeController1(SchoolContext context)
{
_context = context;
}
// GET: HomeController1
public IActionResult Index()
{
List<QuestionCommentViewModel> QCVM = new List<QuestionCommentViewModel>();
QCVM= GetQCVM();
// Console.WriteLine("qqqqqqq");
return View(QCVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(List<QuestionCommentViewModel> QCVM)
{
if (ModelState.IsValid)
{
}
return View();
}
private IQueryable<Question> getQustion()
{
var one = _context.Questions.Include(q => q.QidNavigation);
return one;
}
private List<QuestionCommentViewModel> GetQCVM()
{
Console.WriteLine("111222222222222222222");
var ListQuestion = getQustion();
List<QuestionCommentViewModel> QCVM=new List<QuestionCommentViewModel> ();
foreach (var item in ListQuestion)
{
var ch = _context.Choices.Include(q => q.QidNavigation).Where(q=>q.Qid==item.Id);
QCVM.Add(new QuestionCommentViewModel() { OneQuestions = item, ListChoices= ch });
// return QCVM;
}
return QCVM;
}
// GET: HomeController1/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: HomeController1/Create
public ActionResult Create()
{
return View();
}
// POST: HomeController1/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: HomeController1/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: HomeController1/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: HomeController1/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: HomeController1/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
}
}

You need to change your code like below
#foreach (var item in Model)
{
<h3>#item.OneQuestions.TextQ</h3>
#foreach (var r in item.ListChoices)
{
<input type="radio" id="#r.Id" asp-for="#item.CheckAns" value="#r.TextCh">
<label for="#r.Id">#r.TextCh</label><br>
}
<span asp-validation-for="#item.CheckAns" class="text-danger"></span>
}
Test Result:

Related

Blazor WebAssembly with identity server passing username through form

I am new to Blazor WebAssembly. I have a simple page that allows users to register a company. It takes the company name, description and the username. At the moment the username is entered by the user but I want to automatically grab the username of the logged in user and post it without the need of user input. Here is my page:
#page "/companies/create"
#attribute [Authorize]
#inject HttpClient Http
#inject NavigationManager Navigation
<h3>Register your company</h3>
<AuthorizeView>
Hello, #context.User.Identity.Name!
</AuthorizeView>
<EditForm Model="Companies" OnValidSubmit="#HandleValidSubmit">
<DataAnnotationsValidator />
<div class="form-group">
<label class="control-label">Name</label>
<InputText #bind-Value="Companies.Name" class="form-control" />
<ValidationMessage For="#(() => Companies.Name)" />
</div>
<div class="form-group">
<label class="control-label">Description</label>
<InputText #bind-Value="Companies.Description" class="form-control" />
<ValidationMessage For="#(() => Companies.Description)" />
</div>
<div class="form-group">
<label class="control-label">Username</label>
<InputText #bind-Value="Companies.Username" class="form-control"/>
<ValidationMessage For="#(() => Companies.Username)" />
</div>
<button type="submit" class="btn btn-primary">
<i class="fas fa-save"></i> Register
</button>
</EditForm>
#code {
private Sprelo.Shared.Companies Companies { get; set; } = new Sprelo.Shared.Companies();
private async void HandleValidSubmit()
{
try
{
var response = await Http.PostAsJsonAsync($"/api/companies", Companies);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var companies = JsonConvert.DeserializeObject<Sprelo.Shared.Companies>(content);
Navigation.NavigateTo($"Companies/edit/{companies.Id}");
}
catch (AccessTokenNotAvailableException exception)
{
exception.Redirect();
}
catch (Exception e)
{
}
}
}
This is my model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sprelo.Shared
{
public class Companies
{
[Key]
public Guid Id { get; set; }
[Required]
public String Name { get; set; }
public String Description { get; set; }
public String Username { get; set; }
}
}
and this is an auto generated API controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Sprelo.Server.Data;
using Sprelo.Shared;
namespace Sprelo.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CompaniesController : ControllerBase
{
private readonly ApplicationDbContext _context;
public CompaniesController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/Companies
[HttpGet]
public async Task<ActionResult<IEnumerable<Companies>>> GetCompanies()
{
return await _context.Companies.ToListAsync();
}
// GET: api/Companies/5
[HttpGet("{id}")]
public async Task<ActionResult<Companies>> GetCompanies(Guid id)
{
var companies = await _context.Companies.FindAsync(id);
if (companies == null)
{
return NotFound();
}
return companies;
}
// PUT: api/Companies/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutCompanies(Guid id, Companies companies)
{
if (id != companies.Id)
{
return BadRequest();
}
_context.Entry(companies).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CompaniesExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Companies
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<Companies>> PostCompanies(Companies companies)
{
_context.Companies.Add(companies);
await _context.SaveChangesAsync();
return CreatedAtAction("GetCompanies", new { id = companies.Id }, companies);
}
// DELETE: api/Companies/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteCompanies(Guid id)
{
var companies = await _context.Companies.FindAsync(id);
if (companies == null)
{
return NotFound();
}
_context.Companies.Remove(companies);
await _context.SaveChangesAsync();
return NoContent();
}
private bool CompaniesExists(Guid id)
{
return _context.Companies.Any(e => e.Id == id);
}
}
}
I have been struggling with this for quite a while, any help would be appriciated!
Inject the AuthenticationStateProvider object into your component like this:
#inject AuthenticationStateProvider authProvider
Override the OnInitialized life cycle method:
protected override void OnInitialized ()
{
var authenticationStateTask = await
authProvider.GetAuthenticationStateAsync();
var user = authenticationStateTask.User;
// Check if the user is authenticated
if (user.Identity.IsAuthenticated)
{
// Grab the user name and assign it to Companies.Username
Companies.Username = user.Identity.Name
}
}

Validation failed: InvalidRoleName

I have some problem with the code. I'm not able to create a role. The code seems fine to me, but I'm not able to find the error. With WriteLine I'm getting the following message:
Microsoft.AspNetCore.Identity.RoleManager: Warning: Role 38676182-f211-47d7-b69b-f190e4338123 validation failed: InvalidRoleName.
Why InvalidRoleName is invalid? It's just a string. Any help is appreciated.
c#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Sarpinos.Pages.Admin
{
public class CreateRoleModel : PageModel
{
private readonly RoleManager<IdentityRole> _roleManager;
public CreateRoleModel(RoleManager<IdentityRole> roleManager)
{
_roleManager = roleManager;
}
[BindProperty]
public List<IdentityRole> Roles { get; set; }
public void OnGet()
{
}
public async Task<IActionResult> OnPost()
{
if (ModelState.IsValid)
{
var newRole = new IdentityRole();
newRole.Id = Guid.NewGuid().ToString();
await _roleManager.CreateAsync(newRole);
Console.WriteLine($"{newRole.Id} {newRole.Name}");
}
return RedirectToPage("Dashboard");
}
}
}
cshtml:
#page
#model Sarpinos.Pages.Admin.CreateRoleModel
#{
ViewData["Title"] = "Register";
}
<div class="container">
<form asp-page="CreateRole" method="POST">
<div class="form-group">
<label asp-for="#Model.Roles">Role name:</label>
<input type="text" asp-for="#Model.Roles" class="form-control" placeholder="Enter role name" />
<span asp-validation-for="#Model.Roles" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-success">Create</button>
</form>
</div>
[BindProperty]
public List<IdentityRole> Roles { get; set; }
public void OnGet()
{
}
public async Task<IActionResult> OnPost()
{
if (ModelState.IsValid)
{
var newRole = new IdentityRole();
newRole.Id = Guid.NewGuid().ToString();
await _roleManager.CreateAsync(newRole);
Console.WriteLine($"{newRole.Id} {newRole.Name}");
}
return RedirectToPage("Dashboard");
}
According to your description, it seems that you want to create a new Role, but by using the above code, it looks that you are using a List<IdentityRole> to display the roles and in the post method, you didn't set the role name for the newRole. So, it might cause the issue.
To Create new Role, in the CreateRoleModel, you could create a new class which contains the Role related properties. For example:
public class CreateRoleModel : PageModel
{
private readonly RoleManager<IdentityRole> _roleManager;
public CreateRoleModel(RoleManager<IdentityRole> roleManager) { _roleManager = roleManager; }
public class NewRole
{
public string RoleName { get; set; }
}
[BindProperty]
public NewRole Input { get; set; }
public void OnGet()
{
Input = new NewRole(); //
}
public async Task<IActionResult> OnPostAsync()
{
if (ModelState.IsValid)
{
var newRole = new IdentityRole();
newRole.Id = Guid.NewGuid().ToString();
newRole.Name = Input.RoleName;
await _roleManager.CreateAsync(newRole);
Console.WriteLine($"{newRole.Id} {newRole.Name}");
}
return RedirectToPage("Home/Index");
}
}
Then, in the CreateRole.cshtml page, based on the NewRole class to insert a new role (you could change the namespace to yours).
#page
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#model IdentitySample.Pages.CreateRoleModel
<div class="container">
<form method="POST">
#Html.AntiForgeryToken()
<div class="form-group">
<label asp-for="#Model.Input.RoleName">Role name:</label>
<input asp-for="#Model.Input.RoleName" class="form-control" placeholder="Enter role name" />
<span asp-validation-for="#Model.Input.RoleName" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-success">Create</button>
</form>
</div>

asp.net core - login page doesn't show error message

I have a problem, i new with asp.net core and i try to build Login page (after i finish to build sign up page that add new row to db with the correct information).
my problem is when i click on login button with the wrong details so i don't see the error message (LoginError) only after i click on login button again i see the LoginError message (from TempData), why?
is the right way? if not i will happy to try another way.
Login cshtml page:
#page
#model AutomationTool.Pages.Login.IndexModel
#{
ViewData["Title"] = "Index";
}
<h1>Login</h1>
<form method="post">
<div class="form-group">
<label asp-for="user.UserEmail"></label>
<input asp-for="user.UserEmail" class="form-control" />
<span class="text-danger" asp-validation-for="user.UserEmail"></span>
</div>
<div class="form-group">
<label asp-for="user.Password"></label>
<input asp-for="user.Password" class="form-control" />
<span class="text-danger" asp-validation-for="user.Password"></span>
</div>
<div>
#Model.LoginError
</div>
<div>
#Model.Message
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
Login cshtml.cs page:
namespace AutomationTool.Pages.Login
{
public class IndexModel : PageModel
{
private readonly IUserData userData;
[BindProperty]
public User user { get; set; }
[TempData]
public string Message { get; set; }
[TempData]
public string LoginError { get; set; }
public IndexModel(IUserData userData)
{
this.userData = userData;
}
public IActionResult OnGet()
{
return Page();
}
public IActionResult OnPost()
{
ModelState.Remove("User.Id");
ModelState.Remove("User.FirstName");
ModelState.Remove("User.LastName");
if (!ModelState.IsValid)
{
TempData["Message"] = "All fields required!";
return Page();
}
if (!userData.VerifyLogin(user.UserEmail, user.Password))
{
TempData["LoginError"] = "Something wrong try again!";
return Page();
}
else
{
return RedirectToPage("/Index");
}
}
}
}
thanks!
Here your Message and LoginError parameters have been read many times instead of once, so you should use [BindProperty] or [ViewData] instead of [TempData] to bind these two parameters.
The difference between them, you can refer to this.
Chang your code like this:
public class IndexModel : PageModel
{
private readonly IUserData userData;
[BindProperty]
public User user { get; set; }
[BindProperty]//[ViewData]
public string Message { get; set; }
[BindProperty]//[ViewData]
public string LoginError { get; set; }
public IndexModel(IUserData userData)
{
this.userData = userData;
}
public IActionResult OnGet()
{
return Page();
}
public IActionResult OnPost()
{
ModelState.Remove("User.Id");
ModelState.Remove("User.FirstName");
ModelState.Remove("User.LastName");
if (!ModelState.IsValid)
{
Message = "All fields required!";
return Page();
}
if (!userData.VerifyLogin(user.UserEmail, user.Password))
{
LoginError = "Something wrong try again!";
return Page();
}
else
{
return RedirectToPage("/Index");
}
}
}
Here is the test result:

ASP.NET binding partial View droplist

My code is similar to:
class StudentsViewModel:
public class StudentsViewModel
{
public List<Student> Students { get; set; }
public Student SelectedStudent { get; set; }
public string DisplayMode { get; set; }
}
StudentsController:
[HttpPost]
public ActionResult New(int? page, int? SelectedGroup)
{
// some code
StudentsViewModel model = new StudentsViewModel();
model.Students = db.Students.ToList().ToPagedList(pageNumber, pageSize);
model.SelectedStudent = null;
model.DisplayMode = "WriteOnly";
ViewBag.IDGroup = new SelectList(db.Groups, "IDGroup", "Name");
return View("Index", model);
}
View: Index
<form method="post">
<input type="submit" value="Add Student" formaction="/Students/new" class="btn btn-default" />
//some code
#{
if (Model.SelectedStudent != null)
{
if (Model.DisplayMode == "ReadWrite")
{
Html.RenderPartial("_EditStudent", Model.SelectedStudent);
}
}
if (Model.DisplayMode == "WriteOnly")
{
Html.RenderPartial("_InsertStudent", new StudentList.Models.Student());
}
}</form>
Partial View:
_InsertStudent.cshtml
<div class="form-group">
#Html.DropDownList("IDGroup", String.Empty)
#Html.ValidationMessageFor(model => model.IDGroup)
</div>
I have very big problem because my DropDownList doesn't work... Now I display _InsertStudent when I click on button but it doesn't work... If i have
Html.RenderPartial("_InsertStudent", new StudentList.Models.Student());
directly (without button) it works...

The column name is not valid. [ Node name (if any) = Extent2,Column name = Course_CourseId ]

I always received this error as stated above.
I've recreated the Front Model and also the Front Controller yet I've received the same problem.
Front Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Module1.Models
{
public class Front
{
public int FrontId { get; set; }
public int ModuleId { get; set; }
public string Description { get; set; }
public string Code { get; set; }
public int TotalHrs { get; set; }
public int LectHrs { get; set; }
public int TutHrs { get; set; }
public int PracHrs { get; set; }
public int Year { get; set; }
public string Prerequisite { get; set; }
public virtual Module Module { get; set; }
}
}
Front Controller
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Module1.Models;
namespace Module1.Controllers
{
public class FrontController : Controller
{
private SchoolEntities db = new SchoolEntities();
//
// GET: /Topic/
public ViewResult Index()
{
var fronts = db.Fronts.Include(t => t.Module);
return View(fronts.ToList());
}
//
// GET: /Topic/Details/5
public ViewResult Details(int id)
{
var mod = db.Modules.Include("Fronts").Single(t => t.ModuleId == id);
return View(mod);
}
//
// GET: /Topic/Create
public ActionResult Create(int ID)
{
var modules = db.Modules.Where(m => m.ModuleId == ID).FirstOrDefault();
if (modules != null)
{
ViewBag.Code = modules.Code;
ViewBag.Description = modules.Description;
}
Front model = new Front();
model.ModuleId = ID;
return View(model);
}
//
// POST: /Topic/Create
[HttpPost]
public ActionResult Create(Front front)
{
if (ModelState.IsValid)
{
db.Fronts.Add(front);
db.SaveChanges();
return RedirectToAction("Details", new { id = front.ModuleId });
}
ViewBag.ModuleId = new SelectList(db.Modules, "ModuleId", "Code", front.ModuleId);
return View(front);
}
//
// GET: /Topic/Edit/5
public ActionResult Edit(int id)
{
var modules = db.Modules.Where(m => m.ModuleId == id).FirstOrDefault();
if (modules != null)
{
ViewBag.Code = modules.Code;
ViewBag.Description = modules.Description;
}
Front front = db.Fronts.Find(id);
ViewBag.ModuleId = new SelectList(db.Modules, "ModuleId", "Code", front.ModuleId);
return View(front);
}
//
// POST: /Topic/Edit/5
[HttpPost]
public ActionResult Edit(Front front)
{
if (ModelState.IsValid)
{
db.Entry(front).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", new { id = front.ModuleId });
}
ViewBag.ModuleId = new SelectList(db.Modules, "ModuleId", "Code", front.ModuleId);
return View(front);
}
//
// GET: /Topic/Delete/5
public ActionResult Delete(int id)
{
Front front = db.Fronts.Find(id);
return View(front);
}
//
// POST: /Topic/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Front front = db.Fronts.Find(id);
db.Fronts.Remove(front);
db.SaveChanges();
return RedirectToAction("Details", new { id = front.ModuleId });
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
The error above pops up when it is proceeding to my Front Details
Front Details View
#model Module1.Models.Front
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<fieldset>
<legend>Front</legend>
<div class="display-label">Module</div>
<div class="display-field">
#Html.DisplayFor(model => model.Module.Code)
</div>
<div class="display-label">ModuleName</div>
<div class="display-field">
#Html.DisplayFor(model => model.Description)
</div>
<div class="display-label">ModuleCode</div>
<div class="display-field">
#Html.DisplayFor(model => model.Code)
</div>
<div class="display-label">TotalHrs</div>
<div class="display-field">
#Html.DisplayFor(model => model.TotalHrs)
</div>
<div class="display-label">LectHrs</div>
<div class="display-field">
#Html.DisplayFor(model => model.LectHrs)
</div>
<div class="display-label">TutHrs</div>
<div class="display-field">
#Html.DisplayFor(model => model.TutHrs)
</div>
<div class="display-label">PracHrs</div>
<div class="display-field">
#Html.DisplayFor(model => model.PracHrs)
</div>
<div class="display-label">Year</div>
<div class="display-field">
#Html.DisplayFor(model => model.Year)
</div>
<div class="display-label">Prerequisite</div>
<div class="display-field">
#Html.DisplayFor(model => model.Prerequisite)
</div>
</fieldset>
<p>
#Html.ActionLink("Edit", "Edit", new { id=Model.FrontId }) |
#Html.ActionLink("Back to List", "Index")
</p>
<p>
#Html.ActionLink("Add Record", "Create", new { id = Model.ModuleId})
</p>
<p>
#Html.ActionLink("Back to Home", "Index", "SchoolManager")
</p>
MY ERROR
The column name is not valid. [ Node name (if any) = Extent2,Column name = Course_CourseId ]

Resources