Hy,
I've a json file with list of countries in my contentroot.
It looks like this
{
"countries": [
{
"name": "Afghanistan",
"cca2": "af",
"code": 93
},
{
"name": "Albania",
"cca2": "al",
"code": 355
},
{
"name": "Algeria",
"cca2": "dz",
"code": 213
}
]
}
I want to populate that list of countires to my dropdownlist which is in my Views as asp-items=#Model.Countrydropdownlist from my controller but I get null exceptions.
System.NullReferenceException: 'Object reference not set to an instance of an object.'
I tried to deserilize my json file in model class like this
public class AccountController : Controller
{
//Other stuffs
private readonly IWebHostEnvironment _env;
public AccountController(IWebHostEnvironment env)
{
_env = env
}
public void OnGet(Registration registration)
{
registration.CountryDropDownList = GetCountryItems();
}
public List<SelectListItem> GetCountryItems()
{
string filepath = Path.Combine(_env.ContentRootPath, "CountryList.json");
string jsonlist = System.IO.File.ReadAllText(filepath);
var result = JsonConvert.DeserializeObject<RootCountry>(jsonlist);
List<SelectListItem> _countrydropdownlist = new List<SelectListItem>();
foreach (var nation in result.Countries)
{
_countrydropdownlist.Add(new SelectListItem { Value = nation.Code.ToString(), Text = nation.Name });
}
return _countrydropdownlist;
}
I believe my void OnGet is not being hit.
Update- My full view code.
#model TravelMate.ModelFolder.RegistrationModel.Registration
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, shrink-to-fit=no" />
#{
ViewBag.Title = "Registration";
}
<link href="~/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col text-center">
<br />
<img src="~/Image/GeneralUser.jpg" width="200" height="400" />
<br />
<h3>User Registration</h3>
</div>
<form method="post">
<br />
<h3>Person Details</h3>
<div asp-validation-summary="All" class="text-danger"></div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label asp-for="DateOfBirth"></label>
<input asp-for="DateOfBirth" class="form-control" />
<span asp-validation-for="DateOfBirth" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Mobile"></label>
<input asp-for="Mobile" class="form-control" />
<span asp-validation-for="Mobile" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<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>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Country"></label>
<select asp-for="Country" asp-items="#Model.CountryDropDownList">
<option selected disabled> ---Select Country---</option>
</select>
<span asp-validation-for="Country" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label asp-for="Gender"></label>
<select asp-for="Gender" class="form-control">
<option value="0" selected disabled>Select Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<span asp-validation-for="Gender" class="text-danger"></span>
</div>
</div>
</div>
<br />
<h3>Sign-in Details</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label asp-for="UserName">User Name</label>
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
</div>
<div class="col-md-4">
<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>
<div class="col-md-4">
<div class="form-group">
<label asp-for="ConfirmPassword"></label>
<input asp-for="ConfirmPassword" class="form-control" />
<span asp-validation-for="ConfirmPassword" class="text-danger"></span>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
<script src="~/jquery/jquery.slim.min.js"></script>
<script src="~/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
My error-
Null Exception Error
Error in quickwatch.
I want to populate that list of countires to my dropdownlist
To achieve your requirement, you can refer to the following code snippet.
RegistrationModel class
public class RegistrationModel : PageModel
{
private IWebHostEnvironment _env;
public string Country { get; set; }
public List<SelectListItem> Countrydropdownlist { get; set; }
public RegistrationModel(IWebHostEnvironment env)
{
_env = env;
}
public void OnGet()
{
Countrydropdownlist = GetCountryItems();
}
public List<SelectListItem> GetCountryItems()
{
var filepath = Path.Combine(_env.ContentRootPath, "countrylist.json");
var jsonlist = System.IO.File.ReadAllText(filepath);
var result = JsonConvert.DeserializeObject<RootCountry>(jsonlist);
List<SelectListItem> _countrydropdownlist = new List<SelectListItem>();
foreach (var nation in result.Countries)
{
_countrydropdownlist.Add(new SelectListItem { Value = nation.Code.ToString(), Text = nation.Name });
}
return _countrydropdownlist;
}
}
In Registration.cshtml
<select asp-for="Country" asp-items="Model.Countrydropdownlist"></select>
The countrylist.json file is stored as below
Test Result
Note: for more information about Content root and Web root, please check following doc
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/?view=aspnetcore-3.1&tabs=windows#content-root
Update:
Based on your new update, it seems that you'd like to populate and display dropdown in MVC project, to achieve it, please refer to following example.
public class AccountController : Controller
{
private readonly IWebHostEnvironment _env;
public AccountController(IWebHostEnvironment env)
{
_env = env;
}
public IActionResult Index()
{
ViewBag.Countrydropdownlist = GetCountryItems();
return View();
}
//...
In Index.cshtml file under Views/Account folder
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<select name="Country" asp-items="ViewBag.Countrydropdownlist"></select>
Besides, you can know more about view discovery and how to pass data to views from this doc:
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/overview?view=aspnetcore-3.1#passing-data-to-views
Update2:
It seems that you pass items and populate <select> using viewmodel data, please make sure you provided and passed data to view from your controller action, like below.
//...
//your code logic here
var model = new Registration
{
CountryDropDownList = GetCountryItems()
};
return View(model);
Related
Below is the cshtml code to display AddBooking view and I am not getting drop down in RoomType below.
#model Booking
#inject SignInManager<IdentityUser> SignInManager
#{
var rooms = ViewData["RoomTypes"] as List<SelectListItem>;
}
<h1>Add Booking</h1>
<hr />
#if (SignInManager.IsSignedIn(User))
{
<div class="row">
<div class="col-md-6">
<form asp-action="AddBooking" method="post">
<div asp-validation-summary="ModelOnly" claclass="text-danger"></div>
<div class="form-group">
<label asp-for="ChecKIn" class="control-label"></label>
<input asp-for="ChecKIn" class="form-control" />
<span asp-validation-for="ChecKIn" class="text-danger"></span>
</div>
<div>
<label asp-for="CheckOut" class="control-label"></label>
<input asp-for="CheckOut" class="form-control" />
<span asp-validation-for="CheckOut" class="text-danger"></span>
</div>
//this id is the part where the dropdown is supposed to happen
<div class="form-group">
<label asp-for="RoomType" class="control-label"></label>
<select asp-for="RoomTypeId" asp-items="rooms" class="form-control"></select>
</div>
<div class="form-group">
<label asp-for="NumberOfRooms" class="control-label"></label>
<input asp-for="NumberOfRooms" class="form-control" />
<span asp-validation-for="NumberOfRooms" class="text-danger"></span>
</div>
<br>
<div class="form-group">
<button type="submit" class="btn btn-primary">BookRoom</button>
</div>
</form>
</div>
</div>
}
#section Scripts{
#{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}
I am looking for where I am making a mistake as it is not showing the dropdown options and the type of room should be accessed from database and should be able to display in dropdown, and how to set availability of rooms in room table false once we book the room from bOoking view?
Here is the link of github if you need more details:
link=https://github.com/meprigesh/HotelReservationwithsec.git
You need configure ViewData["RoomTypes"] in AddBooking action like below to populate the dropdown:
[Route("api/[controller]/[action]")]
[ApiController]
public class BookingController : Controller
{
private readonly HotelReservationContext context;
public BookingController(HotelReservationContext context)
{
this.context = context;
}
[HttpGet]
public IActionResult AddBooking()
{
ViewData["RoomTypes"] = context.RoomTypes.Select(
c => new SelectListItem
{
Value = c.RoomTypeId.ToString(),
Text = c.TypeOfRoom
}).ToList();
return View();
}
}
because I need to create my user info in many different tables with many different Models and views I used this code in the address page but as shown in my remarks I lost the user info in the post function My question is why and what to do????? by the way when I copied the User1 difenation from my OnGet function to the OnPost function this code work perfectly as explained in my comment but I still want to understand why a public property lose the information please read my comments
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using RazorPagesUI.Models;
namespace RazorPagesUI.Pages.Forms
{
partial class AddAddressModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public AddAddressModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
[BindProperty(SupportsGet = true)]
public string Mail { get; set; }
public IEnumerable<SelectListItem>? Country { get; set; }
[BindProperty]
public AddressModel? Address { get; set; }
public string SelectedString { get; set; }
public UserModel User1 { get; set; }=new UserModel();
public void OnGet()
{
List<string> TagIds = Mail.Split(',').ToList();
Int32.TryParse(TagIds[0], out int j);
User1.Id = j;
User1.Email = TagIds[1];
User1.FirstName = TagIds[2];
User1.LastName = TagIds[3];
User1.Password = TagIds[4]
Country = new SelectListItem[]
{
new SelectListItem ("Canada", "Canada"),
new SelectListItem ("Egypt", "Egypt"),
new SelectListItem ( "Usa", "Usa")
};
}
public IActionResult OnPost()
{
//when I get to here User1 is null
Address.Country = Request.Form["country"];
if (ModelState.IsValid == false)
{
return Page();
}
//I need to insert my user info to my user table but User1 is null
//here I insert Address info
return RedirectToPage("/index", new{ Name = User1.Firstname);//User1
becomes Null
}
}
}
cshtml file As asked to include in my post
#page
#using RazorPagesUI.Models
#model RazorPagesUI.Pages.Forms.AddAddressModel
#{
ViewData["Title"] = "Add Address";
}
<b>Adderres for: #Model.User1.FirstName #Model.User1.LastName</b>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
<div class="text-center">
<h1>Add Address</h1>
</div>
<form method="post">
<div class="container-fluid">
<div class="p-1">
<div class="text-center">
<select name = "country" asp-items="#Model.Country">
</select>
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.State" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.City"
/>
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.StreetNumber"
placeholder="Street #" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.StreetName"
placeholder="Street Name" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.AppNumber"
placeholder="App#" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.ZipCode" />
</div>
</div>
<div class="p-1">
<div class="text-center">
<input type="tel" asp-for="Address.Phone" />
</div>
</div>
<div class="p-1">
<div class="text-center">
<input type="tel" asp-for="Address.CellPhone" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<button type="submit">Submit</button>
</div>
</div>
</div>
</form>
Firstly,you need to pass User1.FirstName when form post,so that you can get User1.FirstNamein OnPost handler.
form(add hidden input with User1.FirstName):
<form method="post">
<div class="container-fluid">
<div class="p-1">
<div class="text-center">
<select name = "country" asp-items="#Model.Country">
</select>
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.State" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.City"
/>
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.StreetNumber"
placeholder="Street #" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.StreetName"
placeholder="Street Name" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.AppNumber"
placeholder="App#" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.ZipCode" />
</div>
</div>
<div class="p-1">
<div class="text-center">
<input type="tel" asp-for="Address.Phone" />
</div>
</div>
<div class="p-1">
<div class="text-center">
<input type="tel" asp-for="Address.CellPhone" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="hidden" asp-for="User1.FirstName" />
<button type="submit">Submit</button>
</div>
</div>
</div>
</form>
cshtml.cs(If you want to bind the data to User1,you need to use [BindProperty],so that you can use User1.Firstname in OnPost handler):
[BindProperty]
public UserModel User1 { get; set; } = new UserModel();
You have to show your cshtml file i.e. the front end of the Razor page for a more clear description of your problem. But in general, I'm seeing that you are trying to bind a property called Country of a complex object called Address of type AddressModel In this case the name of the input/select in your cshtml file should reflect the complex path to the target Country property of the Address object. It should be something like this <select name="Address.Country" asp-items="Model.Country"></select> Notice the name of the select element Address.Country i.e. it reflects the full path to the target property. More information on complex model binding in razor pages here https://www.learnrazorpages.com/razor-pages/model-binding If you manage to bind the property of the complex object correctly this line of code Address.Country = Request.Form["country"]; becomes redundant. The value of Address.Country should be populated automatically.
im working on a .net core 3.1 razor pages project, i have a form that has a submit button but when i click on it execution is not hitting the Post handler in the page model. Im using webApi as well in the same razor pages project
my startup class
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages()
.AddNewtonsoftJson()
.AddRazorRuntimeCompilation();
services.AddControllers()
.AddNewtonsoftJson()
.AddRazorRuntimeCompilation();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
//app.UseExceptionHandler("/Error");
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
}
my html
#page
#model CandidateBowl.WebPortal.Pages.JobAdvertisement.AddModel
#{
}
<form method="post" action="/Handlers?handler=Advertisement">
<div class="container-fluid">
<div class="row p-5 border pt-4 my-3 rounded">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="JobAdvertisementModel.CompanyId" />
<div class="col-12 px-3 mb-3 border-bottom text-center text-uppercase">
<h2 class="text-primary">Job Advertisement</h2>
</div>
<div class="col-9 pt-3">
<div class="input-group row mb-3">
<div class="col-md-3 col-sm-12 d-sm-block">
<label asp-for="JobAdvertisementModel.IndustryId"></label>
</div>
<div class="col-md-9 col-sm-12">
<select class="form-select" asp-for="JobAdvertisementModel.IndustryId" asp-items="Model.Options">
<option value=""></option>
</select>
<span class="text-danger" asp-validation-for="JobAdvertisementModel.IndustryId"></span>
</div>
</div>
<div class="input-group row mb-3">
<div class="col-md-3 col-sm-12 d-sm-block">
<label asp-for="JobAdvertisementModel.Title"></label>
</div>
<div class="col-md-9 col-sm-12">
<input class="form-control" asp-for="JobAdvertisementModel.Title" />
<span class="text-danger" asp-validation-for="JobAdvertisementModel.Title"></span>
</div>
</div>
<div class="input-group row mb-3">
<div class="col-md-3 col-sm-12 d-sm-block">
<label asp-for="JobAdvertisementModel.Salary"></label>
</div>
<div class="col-md-9 col-sm-12">
#* use year selector *#
<input class="form-control" asp-for="JobAdvertisementModel.Salary" />
<span class="text-danger" asp-validation-for="JobAdvertisementModel.Salary"></span>
</div>
</div>
<div class="input-group row mb-3">
<div class="col-md-3 col-sm-12 d-sm-block">
<label asp-for="JobAdvertisementModel.Location"></label>
</div>
<div class="col-md-9 col-sm-12">
#* use year selector *#
<input class="form-control" asp-for="JobAdvertisementModel.Location" />
<span class="text-danger" asp-validation-for="JobAdvertisementModel.Location"></span>
</div>
</div>
<div class="input-group row mb-3">
<div class="col-md-3 col-sm-12 d-sm-block">
<label asp-for="JobAdvertisementModel.Role"></label>
</div>
<div class="col-md-9 col-sm-12">
#* use year selector *#
<input class="form-control" asp-for="JobAdvertisementModel.Role" />
<span class="text-danger" asp-validation-for="JobAdvertisementModel.Role"></span>
</div>
</div>
<div class="input-group row mb-3">
<div class="col-md-3 col-sm-12 d-sm-block">
<label asp-for="JobAdvertisementModel.Requirements"></label>
</div>
<div class="col-md-9 col-sm-12">
#* use year selector *#
<textarea class="form-control" asp-for="JobAdvertisementModel.Requirements"></textarea>
<span class="text-danger" asp-validation-for="JobAdvertisementModel.Requirements"></span>
</div>
</div>
<div class="input-group row mb-3">
<div class="col-md-9 offset-3 col-sm-12">
<div class="row">
<div class="col-md-6 col-sm-12">
<button class="btn btn-primary form-control">Save</button>
</div>
<div class="col-md-6 col-sm-12">
#* return to candidate details page *#
<a asp-page="Index" class="btn btn-success form-control">Back To Job Advertisements </a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
#section Scripts{
<script src="~/js/tinMCE.js" type="text/javascript"></script>
}
my code behind
public class AddModel : PageModel
{
private readonly IJobAdvertisementRepository jobAdvertisementRepository;
private readonly IIndustryRepository industryRepository;
public AddModel(IJobAdvertisementRepository jobAdvertisementRepository, IIndustryRepository industryRepository)
{
this.jobAdvertisementRepository = jobAdvertisementRepository;
this.industryRepository = industryRepository;
}
[BindProperty]
public JobAdvertisementModel JobAdvertisementModel { get; set; }
public List<SelectListItem> Options { get; set; }
public async Task<IActionResult> OnGetAsync()
{
Options = industryRepository.GetIndustries().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
return Page();
}
public async Task<IActionResult> OnPostAdvertisementAsync()
{
if (!ModelState.IsValid)
{
Options = industryRepository.GetIndustries().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
return Page();
}
var id = await jobAdvertisementRepository.AddAdvertisement(JobAdvertisementModel);
if (id == 0)
return Page();
return RedirectToPage();//still to decide where it should go
}
}
what could be the issue, any help is will be greatly appreciated
You posted,You have a from that has a submit button I guess you mean this line <button class="btn btn-primary form-control">Save</button> is not working.
try this
<input type="submit" value="Save" class="btn btn-primary form-control"/>
also make sure action="/Handlers?handler=Advertisement" is correct in your form.
Please change
<form method="post" action="/Handlers?handler=Advertisement">
to
<form method="post" asp-page-handler="Advertisement">
This will generate the following HTML:
<form method="post" action="/Add?handler=Advertisement">
And like #PritomSarkar says, fix your button
<input type="submit" value="Save" class="btn btn-primary/>
I have a view page to insert some data.
here is the model:
#model BookListMVC.Models.Book
I need to insert a combobox linked to another table "Categories".
The compiler does not allow me to insert multiple models because that is probably not the right way.
How I can insert a combobox linked to "Categories" that point to book "IdCategory" ?
Here the actual code full inside:
#model BookListMVC.Models.Book
<br />
<h2 class="text-info">#(Model.Id!=0 ? "Edit" : "Create") Book</h2>
<br />
<div class="border container" style="padding:30px;">
<form method="post">
#if (Model.Id != 0)
{
<input type="hidden" asp-for="Id" />}
<div class="text-danger" asp-validation-summary="ModelOnly"></div>
<div class="form-group row">
<div class="col-3">
<label asp-for="Name"></label>
</div>
<div class="col-6">
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-3">
<label asp-for="Author"></label>
</div>
<div class="col-6">
<input asp-for="Author" class="form-control" />
<span asp-validation-for="Author" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-3">
<label asp-for="ISBN"></label>
</div>
<div class="col-6">
<input asp-for="ISBN" class="form-control" />
<span asp-validation-for="ISBN" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-3">
<label asp-for="ISBN"></label>
</div>
<div class="col-6">
<input asp-for="ISBN" class="form-control" />
<span asp-validation-for="ISBN" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-3 offset-3">
<button type="submit" class="btn btn-primary form-control">
#(Model.Id != 0 ? "Update" : "Create")
</button>
</div>
<div class="col-3">
<a asp-action="Index" class="btn btn-success form-control">Back to List</a>
</div>
</div>
</form>
</div>
You can insert the combobox model through ViewBag or ViewData. For example.
public IActionResult Index()
{
//The data can be obtained from database.
ViewBag.Categories = new List<SelectListItem>
{
new SelectListItem{ Text="history", Value="1"},
new SelectListItem{ Text="literature", Value="2"},
};
var model = new Book { Id = 2, Author="author", ISBN="isbn", Name="bookname" };
return View(model);
}
This is the simple combobox in the view.
<div class="form-group row">
<div class="col-3">
<label asp-for="categories"></label>
</div>
<div class="col-6">
<select asp-for="categories" name="CategoryId" asp-items="ViewBag.Categories">
<option>-- select the category --</option>
</select>
<span asp-validation-for="categories" class="text-danger"></span>
</div>
</div>
Model (Categories)
public class Categories
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
Result
You can add a property CategoryId in model Book, even add a property Categories.
public class Book
{
public int CategoryId { get; set; }
public Categories categories { get; set; }
}
If you want to pass the object Categories to the bakend, you can add a hidden input box and relative javascript.
Add hidden box.
<div class="form-group row">
<div class="col-3">
<label asp-for="categories"></label>
</div>
<div class="col-6">
<select onchange="changeName()" asp-for="categories" name="categories.CategoryId" asp-items="ViewBag.Categories">
<option>-- select the category --</option>
</select>
<input type="hidden" name="categories.CategoryName" value="" id="categoryName"/>
<span asp-validation-for="categories" class="text-danger"></span>
</div>
</div>
Add javascript.
#section Scripts{
<script>
function changeName() {
var index = document.getElementById("categories").selectedIndex;
var text = document.getElementById("categories").options[index].text;
document.getElementById("categoryName").value=text
}
</script>
}
Then you can get all data include Categories and can handling Categories table.
For a student project, I want to add default value - in the date field(ReleaseDate) but still have a calendar and the option of choosing a date.
My code in Models/Post.cs:
[Display(Name = "Release Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode =true, DataFormatString = "{0: yyyy-MM-dd}")]
public System.DateTime ReleaseDate { get; set; }
And in View/Posts/Create.cshtml:
<div class="form-group">
<label asp-for="ReleaseDate" class="control-label"></label>
<input asp-for="ReleaseDate" class="form-control" />
<span asp-validation-for="ReleaseDate" class="text-danger"></span>
</div>
I try timur but
Controllers/PostController.cs
Is see only one define of index:
public async Task<IActionResult> Index()
{
return View(await _context.Movie.ToListAsync());
}
And your code:
public IActionResult Index()
{
var model = new Post()
{
ReleaseDate = DateTime.Today
};
return View("View", model);
}
I try to put like that
But there is an error (on https://localhost:numbers/Posts
Views/Posts/Create.cshtml
#model Portal.Models.Post
#{
ViewData["Title"] = "Create -";
}
<h1>Create</h1>
<h4>Post</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="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ReleaseDate" class="control-label"></label>
<input asp-for="ReleaseDate" class="form-control" />
<span asp-validation-for="ReleaseDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Description" class="control-label"></label>
<input asp-for="Description" class="form-control" />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
And Views/Posts/Index.cshtml
#model IEnumerable<Portal.Models.Post>
#{
ViewData["Title"] = "Job Rice -";
}
<!-- Image -->
<section>
<div class="container">
<div class="full-width-image">
<img src="img/background.jpg" alt="">
</div>
</div>
</section>
<div class="text-center">
<h1><a asp-action="Create">Create new offer</a></h1>
</div>
#foreach (var item in Model)
{
<section>
<div class="container">
<!-- Heading -->
<div class="my-5"> </div>
<!-- Grid row -->
<div class="row">
<!-- Grid column -->
<div class="col-sm-12 sm-12">
<!-- Card -->
<div class="card">
<div class="card-header text-center colores">
<h4> <i class="fas fa-poll-h"></i> <a asp-action="Details" asp-route-id="#item.Id"> #Html.DisplayFor(modelItem => item.Title) </a></h4>
</div>
<!-- Card content -->
<form class="card-body">
<div class="row">
<div class="col-sm-12">
<div class="text-center"> #Html.DisplayFor(modelItem => item.Description)</div>
<div class="float-right"> #Html.DisplayFor(modelItem => item.ReleaseDate)</div>
</div>
<div>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a>
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
}
As Tieson T. points in his comment, you have to add the "value" attribute to the "input" tag in your razor page:
<input asp-for="ReleaseDate" class="form-control" value="#DateTime.Today.ToString("yyyy-MM-dd")" />
Of course, you can replace "DateTime.Today" with something else.
It doesn't matter that your browser shows the date in different format, you have to use this one inside the value attribute. I just tested it in an ASP.NET Core 3.1 Razor app and it works.
This should instantiate a default value:
public System.DateTime ReleaseDate { get; set; } = System.DateTime.Today;
alternatively if you need time as well
public System.DateTime ReleaseDate { get; set; } = System.DateTime.Now;
Since Razor views still allow you write html, you could try to define yours as
<div class="form-group">
<label asp-for="ReleaseDate" class="control-label"></label>
<input asp-for="ReleaseDate" class="form-control" value="#Model.ReleaseDate.ToString("yyyy-MM-dd")" />
<span asp-validation-for="ReleaseDate" class="text-danger"></span>
</div>
it should render the current model value as starting point for your input, of course you need to define one before passing it down onto a view:
public IActionResult Index()
{
var model = new Post()
{
ReleaseDate = DateTime.Today
};
return View("View", model);
}
You can use the following Razor syntax for this purpose.
<input type="date" asp-for="ReleaseDate" class="form-control" value=#DateTime.Today.ToString("yyyy-MM-dd") />
You just have to put type=date.