Why am I not getting drop down menu in my cshtml file? - c#

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();
}
}

Related

How do I get the userId to save in the database while submitting the form?

I'm a beginner and well i'm doing a form which is capable to send information to the database but I needed one more thing to be sent and it is the Id from the user who submit.
I'm using identity framework I didn't change at all the template code.
My Submit controller was done using scaffold.
Can you guys explain what am I doing wrong? I tried to search in every corner of internet but I didn't get the answer for my question maybe it's too obvious and didn't notice at all.
The code is right below.
.NET CORE VERSION 3.1
Form.cshtml
```
#page
#model AuthSystem.Areas.Identity.Pages.Form.FormModel
#{
ViewData["Title"] = "Form";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<center>
<h1>Form</h1>
<h4>Submit</h4>
</center>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post" class="row">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="row">
<div class="form-group">
<label asp-for="Submit.NrOperador" class="control-label"></label>
<input asp-for="Submit.NrOperador" class="form-control" />
<span asp-validation-for="Submit.NrOperador" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Submit.Posto" class="control-label"></label>
<input asp-for="Submit.Posto" class="form-control" />
<span asp-validation-for="Submit.Posto" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Submit.Maquina" class="control-label"></label>
<input asp-for="Submit.Maquina" class="form-control" />
<span asp-validation-for="Submit.Maquina" class="text-danger"></span>
</div>
</div>
<div class="row">
<div class="form-group">
<label type="time" asp-for="Submit.Hora" class="control-label"></label>
<input type="time" asp-for="Submit.Hora" class="form-control" />
<span asp-validation-for="Submit.Hora" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Submit.Date" class="control-label"></label>
<input type="date" asp-for="Submit.Date" class="form-control" />
<span asp-validation-for="Submit.Date" class="text-danger"></span>
</div>
</div>
<div class="row">
<div class="form-group">
<label asp-for="Submit.Item122" class="control-label"></label>
<input asp-for="Submit.Item122" class="form-control" />
<span asp-validation-for="Submit.Item122" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Submit.Item132" class="control-label"></label>
<input asp-for="Submit.Item132" class="form-control" />
<span asp-validation-for="Submit.Item132" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Submit.Item212" class="control-label"></label>
<input asp-for="Submit.Item212" class="form-control" />
<span asp-validation-for="Submit.Item212" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Submit.Caract"></label>
<br />
<input type="radio" value="Sim" asp-for="Submit.Caract" class="custom-radio" />
<a> Sim </a>
<br />
<input type="radio" value="Não" asp-for="Submit.Caract" class="custom-radio" />
<a> Não </a>
<span asp-validation-for="Submit.Caract" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-page="./Areas/Identity/Pages/Form/FormList">Back to List</a>
</div>
Form.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using AuthSystem.Models;
namespace AuthSystem.Areas.Identity.Pages.Form
{
public class FormModel : PageModel
{
private readonly AuthSystem.Models.FormContext _context;
public FormModel(AuthSystem.Models.FormContext context)
{
_context = context;
}
public IActionResult OnGet()
{
return Page();
}
[BindProperty]
public Submit Submit { get; set; }
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Submit.Add(Submit);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
}
I'm not sure if I understood your issue. But I think you should using Sessions Collection to catch userId. I assume you have model with property UserId type of string after success login make Session["UserId"]
if (!ModelState.IsValid)
{
return Page();
}
model.UserId = Convert.ToString(Session["UserId"]);
Add it before _Context.SaveChanges()

Why do I receive null values in my controller when I submit a form from a view with multiple forms? With ASP.NET Core 5 MVC

I am developing a web application using ASP.NET Core 5 MVC, in which I seek to make multiple submissions of POST type forms to my controller from a view that receives an IEnumerable (from a model called Result) with which I am filling in dynamically the values of the inputs of each form.
However, when I send one of those forms from the view through the controller, in the controller I only receive an object from the model with all the null or empty values, which tells me that it seems that this data was never sent through the form to my controller.
Is there a better way to accomplish this or how do I pass these values from multiple forms to my controller? In advance an apology if what I am doing is already totally wrong, I have been learning ASP.NET Core MVC for a few days.
CONSIDERATIONS
What I seek to achieve is that the user can enter multiple values that belong to the same model in the same view, since each form although it is the same seeks to update a different record or column in the same model or table, so when the submit of the form is sent to the Controller the view does not change, and only the records in the database are updated with each submit in the view. If there is a better way or correct way to do this, I am willing to change the logic, because as I mentioned, I have been using the Framework for little.
Explained the problem and my goal, I will explain in greater detail the flow and code mentioned:
From the Mechanical method of my controller, I return a list of Objects to their corresponding View, which are brought by a DataBaseContext:
// CONTROLLER() that passes an enumerable list of Objects to View Mechanical.cshtml
public IActionResult Mechanical()
{
IEnumerable<Result> objList = _db.Results;
return View(objList);
}
In the Mechanical() view, I get this list of objects and iterate over it through a forEach() loop, where for each object I create a form that directs to the same controller method called Update(), in which I get the values of the object in null and empty (that being my problem):
// VIEW
#model IEnumerable<FatForm.Models.Result>
#if (Model.Count() > 0)
{
#foreach(var result in Model)
{
<form method="post" asp-action="Update">
<input asp-for="#result.Id" hidden />
<input asp-for="#result.Type" hidden />
<input asp-for="#result.FatId" hidden />
<div class="border p-3">
<div class="form-group row">
<h2 class="text-black-50 pl-3">Edit Result</h2>
</div>
<div class="row">
<div class="col-12">
<div class="form-group row">
<div class="col-3">
<label asp-for="#result.Section"></label>
</div>
<div class="col-3">
<label asp-for="#result.Procedure"></label>
</div>
<div class="col-3">
<label asp-for="#result.ResultDescription"></label>
</div>
<div class="col-3">
<label asp-for="#result.Passed"></label>
</div>
</div>
<div class="form-group row">
<div class="col-3">
<input asp-for="#result.Section" class="form-control" />
</div>
<div class="col-3">
<input asp-for="#result.Procedure" class="form-control" />
</div>
<div class="col-3">
<input asp-for="#result.ResultDescription" class="form-control" />
<span asp-validation-for="#result.ResultDescription" class="text-danger"></span>
</div>
<div class="col-3">
<input asp-for="#result.Passed" class="form-control" />
<span asp-validation-for="#result.Passed" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-8 offset-2 row">
<div class="col">
<input type="submit" class="btn btn-info w-75" value="Save" />
</div>
</div>
</div>
</div>
</div>
</div>
</form>
}
}
else
{
<p>No results created yet</p>
}
#section Scripts{
#{
<partial name="_ValidationScriptsPartial" />
}
}
I'm supposed to be looking to send the form values to the following Update() controller method, in which I get all the object values to null:
// POST Update
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Update(Result obj)
{
if (ModelState.IsValid)
{
_db.Results.Update(obj);
_db.SaveChanges();
//return RedirectToAction("Index");
}
return View(obj);
}
As I explained at the beginning, I hope can help me by indicating what I am doing wrong or in what way I should do it. Thanks in advance for your help.
Model binding looks through the sources for the name pattern prefix.property_name. If nothing is found, it looks for just property_name without the prefix.In your code,the asp-for tag helper will generate the name like:result.propertyName.It could not match with backend model. You need use [Bind(Prefix ="result")] to specify the prefix:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Update([Bind(Prefix ="result")]Result obj)
{
//do your stuff...
}
As for receive IEnumerable parameter in action, firstly you need change your razor view to move the form outside the foreach loop, then you need change the asp-for tag helper tattribute to #Model.ToList()[index].PropertyName:
#model IEnumerable<Result>
#if (Model.Count() > 0)
{
<form method="post" asp-action="Update">
#for (int i = 0; i < Model.Count(); i++)
{
<input asp-for="#Model.ToList()[i].Id" hidden />
<input asp-for="#Model.ToList()[i].Type" hidden />
<input asp-for="#Model.ToList()[i].FatId" hidden />
<div class="border p-3">
<div class="form-group row">
<h2 class="text-black-50 pl-3">Edit Result</h2>
</div>
<div class="row">
<div class="col-12">
<div class="form-group row">
<div class="col-3">
<label asp-for="#Model.ToList()[i].Section"></label>
</div>
<div class="col-3">
<label asp-for="#Model.ToList()[i].Procedure"></label>
</div>
<div class="col-3">
<label asp-for="#Model.ToList()[i].ResultDescription"></label>
</div>
<div class="col-3">
<label asp-for="#Model.ToList()[i].Passed"></label>
</div>
</div>
<div class="form-group row">
<div class="col-3">
<input asp-for="#Model.ToList()[i].Section" class="form-control" />
</div>
<div class="col-3">
<input asp-for="#Model.ToList()[i].Procedure" class="form-control" />
</div>
<div class="col-3">
<input asp-for="#Model.ToList()[i].ResultDescription" class="form-control" />
<span asp-validation-for="#Model.ToList()[i].ResultDescription" class="text-danger"></span>
</div>
<div class="col-3">
<input asp-for="#Model.ToList()[i].Passed" class="form-control" />
<span asp-validation-for="#Model.ToList()[i].Passed" class="text-danger"></span>
</div>
</div>
</div>
</div>
</div>
}
<div class="form-group row">
<div class="col-8 offset-2 row">
<div class="col">
<input type="submit" class="btn btn-info w-75" value="Save" />
</div>
</div>
</div>
</form>
}
else
{
<p>No results created yet</p>
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Update(IEnumerable<Result> obj)
{
return View("Mechanical", obj);
}
Result:
Here you need to add FromBody attribute in your action method parameter.
public IActionResult Update([FromBody]Result obj)
{
.....
}

Insert a combobox inside view in .NET Core

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.

populate dropdownlist in View

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);

DateTime default value ASP.net core

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.

Categories