How to pass data from a model as data to a - c#

I have two models Doctor and Patients.
I want to display Names of doctors in a dropdown/select in form for patients.
This is how my Patients Create View Looks like:
#model Application.Models.Patient
#model List<Application.Models.Doctor>
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<link href="~/lib/twitter-bootstrap/css/bootstrap.css" rel="stylesheet" />
<script src="~/lib/jquery/jquery.js"></script>
<script src="~/lib/jquery-validate/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<link href="~/css/StyleSheet.css" rel="stylesheet" />
#{
ViewData["Title"] = "Create";
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/lib/twitter-bootstrap/css/bootstrap.css" rel="stylesheet" />
<title>#ViewBag.Title</title>
</head>
<body>
<div class="container-fluid">
<div class="sidebar">
<nav class="nav flex-column">
<a asp-controller="Home" asp-action="Index" class="nav-item nav-link">Home</a>
<a asp-controller="Home" asp-action="Create" class="nav-item nav-link">Add User</a>
<a asp-controller="Home" asp-action="All" class="nav-item nav-link">All User</a>
</nav>
</div>
<div class="area card">
<div class="card-body" style="background-color: aqua">
<form asp-action="Create" asp-controller="Patient" method="post">
<div class="form-group">
<label asp-for="Name">Patient Name</label>
<div>
<span asp-validation-for="Name" style="color: red;"></span>
</div>
<input asp-for="Name" class="form-control" type="text" id="Name" name="Name" />
</div>
<div class="form-group">
<label asp-for="Adress">Address</label>
<div>
<span asp-validation-for="Adress" style="color: red;"></span>
</div>
<input asp-for="Adress" class="form-control" type="text" id="Adress" name="Adress" />
</div>
<div class="form-group">
<label asp-for="BloodGroup">Blood Group</label>
<select asp-for="BloodGroup" class="custom-select">
<option selected>Custom Select Menu</option>
<option value="A+">A+</option>
<option value="A-">A-</option>
<option value="B+">B+</option>
<option value="B-">B-</option>
<option value="AB+">AB</option>
</select>
</div>
<div class="form-group">
<label asp-for="BloodGroup">Blood Group</label>
#{
<select asp-for="BloodGroup" class="custom-select">
#foreach(var d in ViewBag.doc)
{
<option value="">#d.FirstName</option>
}
</select>
}
</div>
<button class="btn btn-block btn-primary" type="submit">Submit</button>
</form>
</div>
</div>
</div>
</body>
</html>
i am not able to add two models in a single view. I get an warning "the 'model' directive may only occur once per document"
I tried passing, List of Doctors in View as ViewBag but it din't help.
[HttpGet]
public IActionResult Create()
{
ApplicationContext application = new ApplicationContext();
List<Doctor> doctor = application.Doctor.ToList();
ViewBag.Doc = doctor;
return View();
}
What am i missing ? Please help me.

Related

Model Validation in Asp.Net Core Doesnt Work

my model validation doesnt work but every thing is ok I mean I have asp-net-validationin in view and my model have attributes and my submit button send the form with post method to index method in Home controller but the validation not working but the interesting part is that my login validation is work but my main form validation that has all the things that login form has not work I try every thing but no result. but I think the problem can be in the controller. I dont have any idea please help.
Controller
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(User user)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View(user);
}
User Model
public class User
{
[Key]
public int LeadId { get; set; }
[Display(Name ="name")]
[Required(ErrorMessage = "please enter your name")]
[MaxLength(50,ErrorMessage ="the max is 50")]
public string FirstName { get; set; }
[Display(Name = "family")]
[Required(ErrorMessage = "please enter your family")]
[MaxLength(50,ErrorMessage = "the max is 50")]
public string LastName { get; set; }
[Display(Name = "email")]
[Required(ErrorMessage = "please enter your email")]
[MaxLength(100,ErrorMessage = "the max is 100")]
[DataType(DataType.EmailAddress)]
public string EMailAddress1 { get; set; }
[Display(Name = "mobile")]
[Required(ErrorMessage = "please enter your mobile")]
[MaxLength(11,ErrorMessage = "the max is 11")]
[DataType(DataType.PhoneNumber)]
public string MobilePhone { get; set; }
[Required(ErrorMessage = "please choose gender")]
public int gender { get; set; }
}
view
#model DataLayer.User
#{
ViewData["Title"] = "welcome to form";
Layout = "/Views/Shared/_Layout.cshtml";
}
<div class="preloader type-preloader d-flex justify-content-center align-items-center">
<img src="/files/preloader/sdf.gif" alt="preloader" />
</div>
<div class="container">
<form method="post" asp-action="Index" asp-controller="Home" name="myForm" id="myForm" class="box box1 col-lg-12 pb-3 pt-3 col-md-12 col-sm-12 col-12">
<div class="row">
#* Name *#
<div class="form-group floating-label-group col-6 col-sm-12 col-xl-12 col-md-6 col-lg-6">
<i class="zmdi zmdi-account namedarkmode namedarkmode1 "></i>
<input asp-for="FirstName" type="text" name="Name" class="Nameinput Nameinput1 name farsiinput jh" lang="fa" required autocomplete="off" title="enter your name" maxlength="50" />
<label asp-for="FirstName" class="floating-label-name floating-label-name1">name:</label><br />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
#* Family *#
<div class="form-group floating-label-group col-6 col-sm-12 col-xl-12 col-md-6 col-lg-6">
<i class="zmdi zmdi-account familydarkmode familydarkmode1 "></i>
<input asp-for="LastName" type="text" name="Family" class="Familyinput Familyinput1 farsiinput family" lang="fa" required autocomplete="off" title="enter your family" maxlength="50" />
<label asp-for="LastName" class="floating-label-family floating-label-family1">family:</label><br />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
</div>
#* Email *#
<div class="row">
<div class="form-group floating-label-group col-12 col-sm-12 col-md-12 col-xl-12 col-lg-12">
<i class="zmdi zmdi-email emaildarkmode emaildarkmode1"></i>
<input asp-for="EMailAddress1" type="email" name="Email" class="Emailinput Emailinput1" autocomplete="off" required title="enter your email" maxlength="100" />
<label asp-for="EMailAddress1" class="floating-label-email floating-label-email1">email:</label>
<span asp-validation-for="EMailAddress1" class="text-danger"></span>
</div>
</div>
#* Mobile *#
<div class="row">
<div class="d-flex align-items-center align-items-baseline col-12">
<div class="form-group floating-label-group">
<i class="zmdi zmdi-phone phonedarkmode phonedarkmode1"></i>
<input asp-for="MobilePhone" type="tel" name="Mobile" class="MobileInput MobileInput1 farsiinput" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" pattern="[0-9]{11}" lang="fa" dir="rtl" autocomplete="off" required title="enter your mobile" maxlength="11" />
<label asp-for="MobilePhone" class="floating-label-mobile floating-label-mobile1">mobile:</label><br />
<span asp-validation-for="MobilePhone" class="text-danger"></span>
</div>
#* Male/Female *#
<div class="form-group d-inline">
<div class="form-check custom-control custom-radio d-inline">
<input class="form-check-input MaleInput MaleInput1" type="radio" id="MaleRadio" name="Gender" />
<label class="form-check-label custom-control-label cl maledarkmode maledarkmode1" for="MaleRadio"> man</label>
</div>
<div class="form-check custom-control custom-radio d-inline">
<input class="form-check-input FemaleInput FemaleInput1" type="radio" id="FemaleRadio" name="Gender" />
<label class="form-check-label custom-control-label cl femaledarkmode femaledarkmode1" for="FemaleRadio"> woman</label>
<small class="text-danger"></small>
</div>
<span asp-validation-for="gender"></span>
</div>
</div>
</div>
#* reCAPTCHA *#
<div class="pt-2">
<div class="d-flex justify-content-start form-group recaptcha">
<div class="g-recaptcha" data-sitekey="6LcZ05gbAAAAAHOBPJu3xvtCkQcB_mMQIVrxGmTd"></div>
</div><br />
<small class="text-danger recaptchaerror mb-6"></small>
</div>
#* button *#
<div class="row pt-3 col-12">
<button class="d-flex justify-content-start btn btn-outline-success" type="submit">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
enter
</button>
</div>
</form>
</div>
layout
#model AdminContent
<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>form</title>
#* material design iconic *#
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/material-design-iconic-font/2.2.0/css/material-design-iconic-font.min.css">
#* bootstrap *#
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link href="/css/bootstrap.min.css" rel="stylesheet" />
#* css *#
<link rel="stylesheet" href="/css/style.css" />
#* fontawsome *#
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<link rel="icon" type="image/x-icon" href="">
</head>
<body class="d-flex justify-content-center align-items-center">
<header class="header">
<nav class="navbar navbar1 d-flex align-items-baseline navbar-expand-sm navbar-toggleable-sm">
<div class="container navtop navtop1">
#* <img src="/files/AdminImages/#Model.IconImageName" />
*# #if (User.Identity.IsAuthenticated)
{
<h1 class="navbar-brand navbar-brand1 d-inline text-secondary">#User.Identity.Name #ViewData["Title"]</h1>
}
else
{
<h1 class="navbar-brand navbar-brand1 d-inline text-secondary">#ViewData["Title"]</h1>
}
#* start dark mode html *#
<div class="container bn">
<div class="sun sun-logo">
<i class="fas fa-sun fonticon"></i>
</div>
<div class="moon moon-logo">
<i class="fas fa-moon fonticon"></i>
</div>
</div>
#* end dark mode html *#
#if (User.Identity.IsAuthenticated)
{
<i class="zmdi zmdi-power icon icon1"></i>
<a asp-action="Logout" asp-controller="Account" class="btn-link">exit</a>
}
else
{
<i class="zmdi zmdi-account-box icon icon1 mb-7 ml-2"></i>
<a asp-action="Admin" asp-controller="Home" class="btn-link text text1 mnb mb-7 text-secondary">Admin</a>
}
</div>
</nav>
</header>
<main class="d-flex flex-row justify-content-start align-items-start">
#RenderBody()
</main>
#* <script src="/lib/jquery/dist/jquery.min.js"></script>
*#
<script src="/js/jquery-3.5.1.min.js"></script>
<script src="/js/index.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/additional-methods.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?hl=fa"></script>
#RenderSection("Scripts", required: false)
</body>
</html>
make sure to include your model name in the razor page. This is how razor knows the ViewModel
#model UserViewModel
Startup.cs
services.AddRazorPages();
RazorPage.cshtml
<form method="post">
<div asp-validation-summary="ModelOnly"></div>
</form>

How to carry over autogenerated GUID onto another page after creating one

I am currently doing a sign-up page and i would like to insert data ( 1 page for 1 table )
After inserting data into the first table and generating the uid, i would like to bring over the generated uid to the next page.I tried to bring over the userid with viewbag on the textbox on the next page. However i end up with 0000-0000-0000-0000 instead. Can i seek some help?
My references are below.
[HttpPost]
public async Task<IActionResult> CreateAccounts(UserDTO userDto)
{
if (!ModelState.IsValid)
{
ViewBag.message = "Form is invalid please check again.";
return View("~/Views/Login/Register.cshtml");
}
string url = BaseUrl + "/User/Dto/" + "Create";
UserModel recievedUserModel = new UserModel();
#region Salting and hashing
byte[] salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
// derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: userDto.Password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 10000,
numBytesRequested: 256 / 8));
#endregion
userDto.Salt = salt;
userDto.Password = hashed;
StringContent content = new StringContent(JsonConvert.SerializeObject(userDto), Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
using var response = await httpClient.PostAsync(url, content);
string apiResponse = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
recievedUserModel = JsonConvert.DeserializeObject<UserModel>(apiResponse);
ViewBag.message = userDto.UserID;
}
else if (!response.IsSuccessStatusCode)
{
ViewBag.message = apiResponse;
}
}
return View("~/Views/Login/Register2.cshtml");
}
[HttpPost("Dto/Create")]
public async Task<IActionResult> CreateUserFromUserDto(UserDTO userDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
UserModel userModel = new UserModel();
if (!_context.User.Any(u => u.Username.Equals(userDto.Username)))
{
userModel = new UserModel()
{
AccessLevel = userDto.AccessLevel,
Username = userDto.Username,
Password = userDto.Password,
Salt = userDto.Salt,
Surname = userDto.Surname,
GivenName = userDto.GivenName,
ContactNo = userDto.ContactNo,
Gender = userDto.Gender,
Email = userDto.Email,
YearOfBirth = userDto.YearOfBirth
};
try
{
_context.User.Add(userModel);
await _context.SaveChangesAsync();
return Ok();
}
catch
{
return BadRequest("Unable to save to database.");
}
}
else
{
return BadRequest("Username exists, try a different username.");
}
}
Here is my HTML code
#model TTSH_ALIVE.DTOs.UserDTO
#using TTSH_ALIVE.ModelObjects
#{ ViewData["Title"] = "Register";
Layout = null; }
<head>
<title>Welcome - TTSH SteWARdS</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" type="image/x-icon" href="~/images/icons/favicon.ico" />
<link rel="stylesheet" type="text/css" href="~/vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="~/fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="~/fonts/Linearicons-Free-v1.0.0/icon-font.min.css">
<link rel="stylesheet" type="text/css" href="~/vendor/animate/animate.css">
<link rel="stylesheet" type="text/css" href="~/vendor/css-hamburgers/hamburgers.min.css">
<link rel="stylesheet" type="text/css" href="~/vendor/select2/select2.min.css">
<link rel="stylesheet" type="text/css" href="~/css/util.css">
<link rel="stylesheet" type="text/css" href="~/css/main.css">
</head>
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100 p-t-50 p-b-0">
<span class="login100-form-error p-t-20 p-b-45">
#ViewBag.error
</span>
<div class="jp-container" style="margin-top:20px">
<h1 class="jp-jumbo"><b>Sign Up</b></h1>
<hr style="width:80px; border:5px solid #a6192e" class="jp-round">
</div>
<div class="jp-row">
<form asp-action="CreateAccounts">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
#*<div class="form-group">
<label asp-for="UserID" class="control-label"></label>
<input asp-for="UserID" class="form-control" />
<span asp-validation-for="UserID" class="text-danger"></span>
</div>*#
<div class="form-group-full">
<label asp-for="Username" class="text-white"></label>
<input asp-for="Username" class="form-control" />
<span asp-validation-for="Username" class="text-white"></span>
</div>
<div class="form-group-full">
<label asp-for="Password" class="text-white"></label>
<input asp-for="Password" class="form-control" type="password" />
<span asp-validation-for="Password" class="text-white"></span>
</div>
<div class="form-group-half">
<label asp-for="GivenName" class="text-white"></label>
<input asp-for="GivenName" class="form-control" />
<span asp-validation-for="GivenName" class="text-white"></span>
</div>
<div class="form-group-half">
<label asp-for="Surname" class="text-white"></label>
<input asp-for="Surname" class="form-control" />
<span asp-validation-for="Surname" class="text-white"></span>
</div>
<div class="form-group-full">
<label asp-for="Gender" class="text-white"></label><br />
<select asp-for="Gender" class="jp-select">
<option selected disabled>---Please select a gender---</option>
<option>Male</option>
<option>Female</option>
<option>Others</option>
</select>
<span asp-validation-for="Gender" class="text-white"></span>
</div>
<div class="form-group-full">
<label asp-for="ContactNo" class="text-white"></label>
<input asp-for="ContactNo" class="form-control" />
<span asp-validation-for="ContactNo" class="text-white"></span>
</div>
<div class="form-group-full">
<label asp-for="Email" class="text-white"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-white"></span>
</div>
<div class="form-group-full">
<label asp-for="YearOfBirth" class="text-white"></label>
<input asp-for="YearOfBirth" class="form-control" />
<span asp-validation-for="YearOfBirth" class="text-white"></span>
</div>
<div class="text-white">
<b>#ViewBag.message</b>
</div>
<div class="form-group-half">
<input type="submit" value="Sign Up" class="jp-btn-86" />
</div>
<div class="form-group-half">
<a asp-area="" asp-controller="Login" asp-action="Index" style="margin-top: 7px" class="login100-form-btn">Back to Login</a>
</div>
</form>
</div>
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
2nd page
#model TTSH_ALIVE.Models.Dependent
#using TTSH_ALIVE.ModelObjects
#{ ViewData["Title"] = "Register";
Layout = null; }
<head>
<title>Welcome - TTSH SteWARdS</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" type="image/x-icon" href="~/images/icons/favicon.ico" />
<link rel="stylesheet" type="text/css" href="~/vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="~/fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="~/fonts/Linearicons-Free-v1.0.0/icon-font.min.css">
<link rel="stylesheet" type="text/css" href="~/vendor/animate/animate.css">
<link rel="stylesheet" type="text/css" href="~/vendor/css-hamburgers/hamburgers.min.css">
<link rel="stylesheet" type="text/css" href="~/vendor/select2/select2.min.css">
<link rel="stylesheet" type="text/css" href="~/css/util.css">
<link rel="stylesheet" type="text/css" href="~/css/main.css">
</head>
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100 p-t-50 p-b-0">
<span class="login100-form-error p-t-20 p-b-45">
#ViewBag.error
</span>
<div class="jp-container" style="margin-top:20px">
<h1 class="jp-jumbo"><b>Sign Up</b></h1>
<hr style="width:80px; border:5px solid #a6192e" class="jp-round">
</div>
<div class="jp-row">
<form asp-action="CreateAccounts">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group-full">
<label asp-for="UserID" class="text-white"></label>
<input asp-for="UserID" value="#ViewBag.message" class="form-control" />
<span asp-validation-for="UserID" class="text-white"></span>
</div>
<div class="form-group-half">
<label asp-for="AgeOfDependent" class="text-white"></label>
<input asp-for="AgeOfDependent" class="form-control" />
<span asp-validation-for="AgeOfDependent" class="text-white"></span>
</div>
<div class="form-group-half">
<label asp-for="DependentType" class="text-white"></label>
<input asp-for="DependentType" class="form-control" />
<span asp-validation-for="DependentType" class="text-white"></span>
</div>
<div class="text-white">
<b>#ViewBag.message</b>
</div>
<div class="form-group-half">
<input type="submit" value="Sign Up" class="jp-btn-86" />
</div>
<div class="form-group-half">
<a asp-area="" asp-controller="Login" asp-action="Index" style="margin-top: 7px" class="login100-form-btn">Back to Login</a>
</div>
</form>
</div>
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

How to use Razor class library inside a ASP.NET Core application

I wrote a simple Razor class library as following
Areas/Library/Pages/_ViewStart.cshtml
#{
Layout = "_Layout";
}
Areas/Library/Pages/Shared/_Login.cshtml
<div class="container">
<h1>Log in</h1>
<div class="row">
<div class="col-md-4">
<section>
<form id="account" method="post" novalidate="novalidate">
<h4>Use a local account to log in.</h4>
<hr>
<div class="text-danger validation-summary-valid" data-valmsg-summary="true">
<ul>
<li style="display:none"></li>
</ul>
</div>
<div class="form-group">
<label for="Input_Email">Email</label>
<input class="form-control" type="email" data-val="true" data-val-email="The Email field is not a valid e-mail address."
data-val-required="The Email field is required." id="Input_Email" name="Input.Email" value="">
<span class="text-danger field-validation-valid" data-valmsg-for="Input.Email" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<label for="Input_Password">Password</label>
<input class="form-control" type="password" data-val="true" data-val-required="The Password field is required." id="Input_Password" name="Input.Password">
<span class="text-danger field-validation-valid" data-valmsg-for="Input.Password" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<div class="checkbox">
<label for="Input_RememberMe">
<input type="checkbox" data-val="true" data-val-required="The Remember me? field is required." id="Input_RememberMe" name="Input.RememberMe" value="true">
Remember me?
</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Log in</button>
</div>
</form>
</section>
</div>
</div>
</div>
Areas/Library/Pages/Shared/_Message.cshtml
<h3>This is a Partial View</h3>
<p>This Partial view cretead as a Razor Class Library</p>
Areas/Library/Pages/Shared/_Register.cshtml
<div class="container">
<h1>Register</h1>
<div class="row">
<div class="col-md-4">
<form method="post" action="/Identity/Account/Register" novalidate="novalidate">
<h4>Create a new account.</h4>
<hr>
<div class="text-danger validation-summary-valid" data-valmsg-summary="true">
<ul>
<li style="display:none"></li>
</ul>
</div>
<div class="form-group">
<label for="Input_Email">Email</label>
<input class="form-control" type="email" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Input_Email" name="Input.Email" value="">
<span class="text-danger field-validation-valid" data-valmsg-for="Input.Email" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<label for="Input_Password">Password</label>
<input class="form-control" type="password" data-val="true" data-val-length="The Password must be at least 6 and at max 100 characters long." data-val-length-max="100" data-val-length-min="6"
data-val-required="The Password field is required." id="Input_Password" maxlength="100" name="Input.Password" aria-autocomplete="list">
<span class="text-danger field-validation-valid" data-valmsg-for="Input.Password" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<label for="Input_ConfirmPassword">Confirm password</label>
<input class="form-control" type="password" data-val="true" data-val-equalto="The password and confirmation password do not match." data-val-equalto-other="*.Password" id="Input_ConfirmPassword"
name="Input.ConfirmPassword">
<span class="text-danger field-validation-valid" data-valmsg-for="Input.ConfirmPassword" data-valmsg-replace="true"></span>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
</div>
Areas/Library/Pages/Page1.cshtml
#page
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<h2>Hello from a Razor UI class library!</h2>
<partial name="_Message" />
Areas/Library/Pages/Page2.cshtml
#page
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<partial name="_Login" />
Areas/Library/Pages/Page3.cshtml
#page
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<partial name="_Register" />
After that, I added it as a dependency to a new web app project, and I changed the Layout
WebApp Layout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - WebApplication1</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">WebApplication1</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
<li class="nav-item">
<a asp-page="/Page3" asp-area="Library" class="nav-link text-dark" >Register</a>
</li>
<li class="nav-item">
<a asp-page="/Page1" asp-area="Library" class="nav-link text-dark" >Page1</a>
</li>
<li class="nav-item">
<a asp-page="/Page2" asp-area="Library" class="nav-link text-dark" >Login</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2020 - WebApplication1 - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
#RenderSection("Scripts", required: false)
</body>
</html>
So, As you can see, I added the below code to the default layout
<li class="nav-item">
<a asp-page="/Page3" asp-area="Library" class="nav-link text-dark" >Register</a>
</li>
<li class="nav-item">
<a asp-page="/Page1" asp-area="Library" class="nav-link text-dark" >Page1</a>
</li>
<li class="nav-item">
<a asp-page="/Page2" asp-area="Library" class="nav-link text-dark" >Login</a>
</li>
The result is looking good
But the razor pages does not work.
There is no content available by clicking, Can anyone help to find out the problem?
Sample Repository: RazorCL
The issue is related that you didn't configure the routing for the Razor page. From your source code, we can see that in the Razor class library, you are creating some Razor pages, and in the WebApplication1, it just configures the MVC routing, without the Razor page routing. So, it will cause this issue.
To solve it, try to register the Razor page routing in the WebApplication1's Startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages(); //razor page routing
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/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(); //razor page routing
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Then, the screenshot as below:

System.Web.HttpException: Section not defined

I have the following _Layout.cshtml:
#using System.Web.Optimization
<!DOCTYPE html>
<html>
<head>
<title>Structured Content </title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
#Scripts.Render("~/bundles/jquery")
</head>
<body>
<div id="layout">
<div id="header">
<div class="menu_header">
<h2 style="float: left;">Logo</h2>
#RenderSection("menu_header");
</div>
</div>
<div id="bottom_menu">
</div>
<div id="media">
#RenderSection("media");
</div>
<div id="content">
<div id="maincontent">
#RenderBody();
</div>
</div>
<div id="footer">
Foooter
</div>
</div>
#RenderSection("scripts", required: false)
</body>
</html>
In my index.cshtml, I have the following:
#{
Layout = "../Shared/_Layout.cshtml";
}
#section menu_header {
<div class="login_menu_links">
<ul>
<li>
Top ranked▼
</li>
</ul>
</div>
<div class="sign_in_style">
<form>
<span style="display:inline-block">
<label>Email</label><br/>
<input type="text" name="email">
</span>
<span style="display:inline-block">
<label>Password</label><br/>
<input type="password" name="pass">
<input type="submit" name="submit" value="Log in">
</span>
</form>
</div>
}
#section media {
<img src="https://marshallamps.com/wp-content/themes/marshallamps/images/brand-video-overlay.jpg" width="755">
<img src="https://www.marshallheadphones.com/media/upload/pressimages/marshall/MIXEDMEDIA/EVENT/instac.jpg">
<img src="http://blog.weddingfavorsbynette.com/wp-content/uploads/2013/05/wedding-music-dj-624x416.jpg" width="498">
}
<div id="leftcontent">
<h2 class="news_title">Get discovered as a band or musician<br />here on Namn. </h2>
<ul class="info_text">
<li><img src="https://cdn3.iconfinder.com/data/icons/vote/16/medal_star_rank-512.png" width="30" height="30">Gather karma points - get ranked</li>
<li><img src="http://findicons.com/files/icons/770/token_dark/128/headphones.png" width="32" height="32">Explore new music - all genres</li>
<li><img src="https://cdn3.iconfinder.com/data/icons/gray-user-toolbar/512/social_network-512.png" width="30" height="30">Connect - with musicians and friends</li>
</ul>
</div>
<script type="text/javascript">
$('#top_ranked_menu').mouseover(function () {
$('#bottom_menu').show();
});
$('#bottom_menu').mouseout(function () {
$(this).hide();
});
</script>
When I run my application, I get the following error message:
Section not defined: "menu_header".
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Section not defined:
"menu_header".
As I can see, I have defined them?

How to call a search method in a _Layout.cshtml?

I'm trying to create a search method, that is called in my _Layout.cshtml and when I click on submit button, the user is redirected to "search view".
I' following this tutorial, but the author call your method at index view and I need to call the method at _Layout to be redirect to another view that will give me the return of method.
This is my _Layout, is basic a nav-bar from bootstrap with a textfield and a button, that the user can put what he need to find:
#model IEnumerable<TestTcc2.Models.Musica>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/Bootstrap")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">#Html.ActionLink("your logo here", "IndexOuvinte", "Home")</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Home", "IndexOuvinte", "Home")</li>
</ul>
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<ul class="nav navbar-nav navbar-right">
<li>#Html.ActionLink("Manage Account", "Manage", "Account")</li>
<li>#using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" }))
{
#Html.AntiForgeryToken()
Log off}</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</div>
<div class="container">
#RenderSection("featured", required: false)
#RenderBody()
</div>
<!--Fim container -->
</body>
</html>
and this is the method that I want to call at _Layout.cshtml:
public ActionResult Search(string search)
{
var musicas = from m in db.Musicas select m;
if (!String.IsNullOrEmpty(search))
{
musicas = musicas.Where(s => s.Nome.Contains(search));
return RedirectToAction("Search"); //name of view that will return the data
}
return View(musicas);
}
Well, you might consider specifying an action to the form or just use the appropriate helper to generate it:
#using (Html.BeginForm("Search", "SomeController", null, FormMethod.Post, new { #class = "navbar-form navbar-left", role = "search" }))
{
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
}

Categories