How to POST in .Net Core MVC - asp.net

i have a login page with Username and Password inputs and also a submit button. I want to call a method in my Controller that checks if the data matches and shows the result. how do i call that method? I tried the following but it didnt work it passes those as parameters
#using (Html.BeginForm("Logmein", "LoginController", FormMethod.Post))
{
<form method="post">
<div class="input-group mt-3">
<div class="input-group-prepend">
</div>
<input type="text" class="form-control" placeholder="Username" asp-for="Userusername">
</div>
<div id="login_usernametxt" class="input-group mt-2">
<input id="login_passwordtxt" type="password" class="form-control" placeholder="Password" asp-for="Userpassword">
</div>
<button id="login_signinbtn" class="mt-3 btn bg-warning text-light" style="float: right;" formmethod="post">Sign in</button>
</form>
}
here is my controller.
public class LoginController : Controller
{
public LoginInfo Logininformation { get; set; }
public IActionResult Userlogin()
{
return View();
}
[HttpPost]
public IActionResult Logmein()
{
//checks if the data matches....
return RedirectToPage("/Home/Index");
}
}

Tyr to include model with following properties Userusername,Userpassword in Logmein() method
Also u can remove html helper method ( #using (Html.BeginForm("Logmein", "LoginController", FormMethod.Post)))
Ex:
<form method = "post" asp-controller = "Login" asp-action = "Logmein" >
<div class="input-group mt-3">
<div class="input-group-prepend">
</div>
<input type="text" class="form-control" placeholder="Username" asp-for="Userusername">
</div>
<div id="login_usernametxt" class="input-group mt-2">
<input id="login_passwordtxt" type="password" class="form-control" placeholder="Password" asp-for="Userpassword">
</div>
<input type = "submit" value = "Login" />
</form>
Model Class
public class Login
{
public string Userusername { get; set; }
public string Userpassword { get; set; }
}
Controller Method:
[HttpPost]
public IActionResult Logmein(LoginModel login)
{
//checks if the data matches....
return RedirectToPage("/Home/Index");
}

Related

How to make selection (choose one of the two strings with select input in html) with Entity Framework?

I want to make the user only choose between two strings, Internal or Consigned, to be inserted into the InternalConsigned column of a database. How do I do that?
This is my current code:
Equipment.cs model class:
public class Equipment
{
[Key]
public int Id { get; set; }
[Required]
[DisplayName("Equipment Name")]
public string Name { get; set; }
[Required]
public int Amount { get; set; }
[Required]
public string Status { get; set; }
[ForeignKey("DepartmentId")]
public int DepartmentId { get; set; }
public Department? Department { get; set; }
[Required]
public string InternalConsigned { get; set; }
public DateTime EOLDate { get; set; }
}
Create action method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Amount,Status,DepartmentId,InternalConsigned,EOLDate")] Equipment equipment)
{
if (ModelState.IsValid)
{
_context.Add(equipment);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "Name", equipment.DepartmentId);
return View(equipment);
}
Create.cshtml:
#model Equipment
#{
ViewData["Title"] = "Create";
}
<h4>Equipment</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Amount" class="control-label"></label>
<input asp-for="Amount" class="form-control" />
<span asp-validation-for="Amount" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Status" class="control-label"></label>
<input asp-for="Status" class="form-control" />
<span asp-validation-for="Status" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DepartmentId" class="control-label"></label>
<select asp-for="DepartmentId" class ="form-control" asp-items="ViewBag.DepartmentId"></select>
</div>
<div class="form-group">
<label asp-for="InternalConsigned" class="control-label"></label>
<input asp-for="InternalConsigned" class="form-control" />
<span asp-validation-for="InternalConsigned" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EOLDate" class="control-label"></label>
<input asp-for="EOLDate" class="form-control" />
<span asp-validation-for="EOLDate" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
I know I have to use the select tag in the View, but I'm not sure what to write in the Controller.
If I don't misunderstand your question, You want to write a dropdown list with two options Internal or Consigned, So you can refer to this simple demo, Hope it can help you.
List<SelectListItem> test = new List<SelectListItem>();
test.Add(new SelectListItem { Text = "Internal ", Value = "Internal " });
test.Add(new SelectListItem { Text = "Consigned", Value = "Consigned" });
ViewData["demo"] = test;
Then in the view:
<select asp-for="InternalConsigned" asp-items="#ViewBag.demo"></select>
Demo:

Razor pages client site validation not working

I'm trying to use client-side validation in my razor pages app but it's not working for the views.
It does work on the register page that is located under the identity area.
Create.cshtml
#model Toolbox.Models.ProjectsModel.Assignment
#{
ViewData["Title"] = "Create";
}
<h1>Nieuwe taak maken</h1>
<h4>Taak</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Fase" class="control-label"></label>
<input asp-for="Fase" class="form-control" />
<span asp-validation-for="Fase" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Maak nieuwe taak" class="btn btn-primary my-2"/>
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index" class="btn btn-primary">Terug</a>
</div>
Assignment.cs
using System.ComponentModel.DataAnnotations;
using Toolbox.Interfaces;
namespace Toolbox.Models.ProjectsModel
{
public class Assignment : IAssignment
{
[Key]
public int Id { get; set; }
[Display(Name = "Naam")]
[Required]
public string Name { get; set; }
[Required]
public string Fase { get; set; }
public List<SubAssignment> SubAssignment { get; set; }
}
}
_ViewImports.cshtml
#using Toolbox
#using Toolbox.Models
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
_viewStart.cshtml
#{
Layout = "_Layout";
}
Program.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "default",
pattern: "{controller=Home}/{action=Index}");
endpoints.MapRazorPages();
});
Does anybody know how I need to solve this problem?
You need to include the _ValidationScriptsPartial file in the Razor page. Add the following to the bottom of the page/view:
#section scripts{
<partial name="_ValidationScriptsPartial" />
}

ASP MVC does not validate model

There is a simple view:
#model Bla.SomeModel
<div class="soket-item">
<form>
<div class="form-group socket-info-group">
<label asp-for="Count" class="control-label"></label>
<input name="Sockets[#index].Count" asp-for="Count" class="form-control" />
<span asp-validation-for="Count" class="text-danger"></span>
</div>
<input type="submit" value="Push!" />
</form>
</div>
And there is a simple model :
public class SomeModel
{
[Required]
[Display(Name = "Charge Count")]
[Range(1, 10)]
public int Count { get; set; }
}
As I set Range attribute I expect a warning to appear when a negative value entering. But that doesn't happen.
Why ?
UPD Controller :
namespace Bla.Controllers
{
[Route("Socket")]
public class MyController : Controller
{
[Route("New")]
public ActionResult NewSocketForm()
{
return View();
}
}
}
Here is the updated code:
Code for UI
#model SomeModel
<div class="soket-item">
<form asp-controller="Home" asp-action="New" method="post" >
<div class="form-group socket-info-group">
<label asp-for="Count" class="control-label"></label>
<input name="Count" type="text" asp-for="Count" class="form-control" />
<span asp-validation-for="Count" class="text-danger"></span>
</div>
<input type="submit" value="Push!" />
</form>
</div>
Code for Controller
[HttpPost]
public IActionResult New(SomeModel someModel)
{
if (!ModelState.IsValid)
{
ViewBag.ErrorMessage = "Invalid Input";
}
// do your things
return View("Index");
}

Why isn't my member information transferring from the razor page to the Controller

My razor view is only sending the two textboxes fields. I need it to either send a field called "isDesigner" which is a bool or I need to be able to retrieve this information in from the database in the controller based on what the "Email" is.
Here is the cshtml
#model Member
#{ ViewData["Title"] = "Index"; }
<div class="row">
<div class="col-md-4">
<form method="post">
<div>
<h4>Login</h4>
<div class="form-group">
<label class="control-label">Email: </label>
<input asp-for="Email" class="form-control" /><span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Password: </label>
<input asp-for="Password" class="form-control" /><span asp-validation-for="Password" class="text-danger"></span>
</div>
<input type="submit" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<label> <a class="nav-link text-dark" asp-area="" asp-controller="Members" asp-action="Register">Register</a></label>
<label> <a class="nav-link text-dark" asp-area="admin" asp-controller="Home" asp-action="Index">Admin</a></label>
This is the controller side
public class MembersController : Controller
{
private readonly ThreeDeePrintingHubContext _context;
private readonly ILogger<MembersController> _logger;
public MembersController(ThreeDeePrintingHubContext threeDeeHubContext, ILogger<MembersController> logger)
{
_context = threeDeeHubContext;
_logger = logger;
}
[HttpPost]
public ActionResult Index(Member member)
{
var isValidMember = _context.Members.Where(x => x.Email == member.Email && x.Password == member.Password).Any();
if (isValidMember)
{
return Redirect("/Product");
}
else
{
TempData["Message"] = "Invalid user";
return View();
}
}
As far as I know, if you want to send the bool value from the view to the controller, you should firstly get it or set it in the view and then send it to the controller.
More details, you could refer to below codes:
<form method="post">
<div>
<h4>Login</h4>
<div class="form-group">
<label class="control-label">Email: </label>
<input asp-for="Email" class="form-control" /><span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Password: </label>
<input asp-for="Password" class="form-control" /><span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">isDesigner: </label>
<input asp-for="isDesigner" class="form-control" /><span asp-validation-for="isDesigner" class="text-danger"></span>
</div>
<input type="submit" class="btn btn-primary" />
</div>
</form>
Member class:
public class Member
{
public string Email { get; set; }
public string Password { get; set; }
public bool isDesigner { get; set; }
}
Result:
[HttpPost]
public ActionResult Index(Member member)
{
This was the answer
var myMember = _context.Members.Where(x => x.Email == member.Email && x.Password == member.Password).FirstOrDefault();
var isValidMember = myMember != null;
if (isValidMember)
{
if (myMember.IsDesigner)
{
return Redirect("/Product/DesignerIndex");
}
else
{
return Redirect("/Product");
}
}
else
{
TempData["Message"] = "Invalid user";
return View();
}
}
// GET: MembersController/Details/5
public ActionResult Details(int id)
{
return View();
}

Form Validation not working in Blazor 3.1

I am using EF to save data in DB and so far farm works fine and saves the data, but when i try to add validation to form it doesnt work & doesnt show any error message or save any data in database.
Example of working & non working code.
Below code without validation
Employee.cs
using System.ComponentModel.DataAnnotations;
namespace BlazorSPA1.Data
{
public class Employee
{
[MaxLength(50)]
public string Id { get; set; }
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(50)]
public string Department { get; set; }
[MaxLength(100)]
public string Designation { get; set; }
[MaxLength(100)]
public string Company { get; set; }
[MaxLength(100)]
public string City { get; set; }
}
}
AddEmployee.razor
#page "/addemployee"
#inject NavigationManager NavigationManager
#inject IEmployeeService EmployeeService
<h2>Create Employee</h2>
<hr />
<form>
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label for="Name" class="control-label">Name</label>
<input for="Name" class="form-control" #bind="#employee.Name" />
</div>
<div class="form-group">
<label for="Department" class="control-label">Department</label>
<input for="Department" class="form-control" #bind="#employee.Department" />
</div>
<div class="form-group">
<label for="Designation" class="control-label">Designation</label>
<input for="Designation" class="form-control" #bind="#employee.Designation" />
</div>
<div class="form-group">
<label for="Company" class="control-label">Company</label>
<input for="Company" class="form-control" #bind="#employee.Company" />
</div>
<div class="form-group">
<label for="City" class="control-label">City</label>
<input for="City" class="form-control" #bind="#employee.City" />
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="button" class="btn btn-primary" #onclick="#CreateEmployee" value="Save" />
<input type="button" class="btn" #onclick="#Cancel" value="Cancel" />
</div>
</div>
</div>
</form>
#code {
Employee employee = new Employee();
protected async Task CreateEmployee()
{
await EmployeeService.CreateEmployee(employee);
NavigationManager.NavigateTo("listemployees");
}
void Cancel()
{
NavigationManager.NavigateTo("listemployees");
}
}
Code which is not working after i made validation changes
Employee.cs
using System.ComponentModel.DataAnnotations;
namespace BlazorSPA1.Data
{
public class Employee
{
[MaxLength(50)]
public string Id { get; set; }
[Required]
[StringLength(20)]
public string Name { get; set; }
[Required]
[StringLength(20)]
public string Department { get; set; }
[MaxLength(100)]
public string Designation { get; set; }
[MaxLength(100)]
public string Company { get; set; }
[MaxLength(100)]
public string City { get; set; }
}
}
AddEmployeeValidation.razor
#page "/addemployeeValidation"
#inject NavigationManager NavigationManager
#inject IEmployeeService EmployeeService
<h2>Create Employee</h2>
<hr />
<EditForm Model="#employee" OnValidSubmit="#CreateEmployee">
<DataAnnotationsValidator />
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label for="Name" class="control-label">Name</label>
<input for="Name" class="form-control" #bind="#employee.Name" />
<ValidationMessage For="#(()=> employee.Name)" />
</div>
<div class="form-group">
<label for="Department" class="control-label">Department</label>
<input for="Department" class="form-control" #bind="#employee.Department" />
</div>
<div class="form-group">
<label for="Designation" class="control-label">Designation</label>
<input for="Designation" class="form-control" #bind="#employee.Designation" />
</div>
<div class="form-group">
<label for="Company" class="control-label">Company</label>
<input for="Company" class="form-control" #bind="#employee.Company" />
</div>
<div class="form-group">
<label for="City" class="control-label">City</label>
<input for="City" class="form-control" #bind="#employee.City" />
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="button" class="btn btn-primary" value="Save" />
<input type="button" class="btn" #onclick="#Cancel" value="Cancel" />
</div>
</div>
</div>
</EditForm>
#code {
Employee employee = new Employee();
protected async Task CreateEmployee()
{
await EmployeeService.CreateEmployee(employee);
NavigationManager.NavigateTo("listemployees");
}
void Cancel()
{
NavigationManager.NavigateTo("listemployees");
}
}
I am using below code example show in this example https://www.c-sharpcorner.com/article/visual-studio-extension-for-blazor-spa-with-ef-core-3-1/
When i add validation code, it open Add Employee page but nothing happens no validation message no form submit even no data is save in database. not sure where issue is
I had made a tiny mistake which went un-noticed, Validation started working when i changed the input type to submit
<input type="button" class="btn btn-primary" value="Save" />
Correct
<input type="submit" class="btn btn-primary" value="Save" />

Resources