How do I get my view to show my database table - asp.net-mvc

i'm new to ASP.net. I am trying to figure out how to get my Edit/Display pages working properly for a multiselect listbox.
My create works fine, and saves to my database, but I cannot figure out how to return to the edit page, and still see the values selected.
Hopes this makes sense.
Here is the code that I have for the create method. The record saves fine in both tables, but I am having trouble getting the values from my Options table.
I want to try to make the Edit view look like the Create View
Controller
[HttpPost]
public IActionResult Create(MusicViewModel model)
{
if(ModelState.IsValid)
{
var album = new Music();
album.Album = model.Album;
album.Artist = model.Artist;
album.Label = model.Label;
album.Review = model.Review;
album.ReleaseDate = model.ReleaseDate;
foreach(Types type in model.Options)
{var opt = new Options();
opt.Music = album;
opt.Types = type;
_musicData.AddOptions(opt);
}
_musicData.Add(album);
_musicData.Commit();
return RedirectToAction("Details", new { id = album.MusicID });
}
return View();
}
Music.cs
public enum Types
{
Spotify,
Groove,
CD,
Vinyl,
Pandora
}
public class Music
{
public int MusicID { get; set; }
[Required]
[MaxLength(50),MinLength(5)]
public string Artist { get; set; }
[Required, MinLength(5)]
public string Album { get; set; }
public int Rating { get; set; }
public Label Label { get; set; }
[DataType(DataType.Date)]
[Display(Name ="Release Date")]
public DateTime ReleaseDate { get; set; }
public string Review { get; set; }
public List<Options> Options { get; set; }
}
public class Options
{
public int OptionsID { get; set; }
public Types Types { get; set; }
public int MusicID { get; set; }
public Music Music { get; set; }
}
public class MusicDbContext:DbContext
{
public DbSet<Music> Albums { get; set; }
public DbSet<Options> Options { get; set; }
}
View
#model Music
....
<form asp-action="Create" method="post">
<div class="row">
<div class="col-md-3 col-md-offset-2">
<fieldset class="form-group">
<label asp-for="Artist"></label>
<input class="form-control" asp-for="Artist" />
<span asp-validation-for="Artist" class="alert"></span>
</fieldset>
</div>
<div class="col-md-3">
<fieldset class="form-group">
<label asp-for="Album"></label>
<input class="form-control" asp-for="Album" />
<span asp-validation-for="Album" class="alert"></span>
</fieldset>
</div>
<div class="col-md-3">
<label asp-for="Label"></label>
#Html.DropDownList("Label", Html.GetEnumSelectList(typeof(Label)), "-------", new { #class = "form-control" })
</div>
</div>
<div class="row">
<div class="col-md-3 col-md-offset-2">
<fieldset class="form-group">
<label asp-for="Options"></label>
<select multiple class="form-control" asp-for="Options"
asp-items="#Html.GetEnumSelectList(typeof(Types))"></select>
</fieldset>
</div>
<div class="col-md-3">
<fieldset class="form-group">
<label asp-for="ReleaseDate"></label>
<input type="text" asp-for="ReleaseDate" class="DateBox form-control" />
<span asp-validation-for="ReleaseDate" class="alert"></span>
</fieldset>
</div>
</div>
<div class="col-md-offset-3"><input class="btn btn-info" type="submit" value="Submit" /></div>
</form>

I figured it out, probably not the most efficient way, but at least the code works
[HttpPost]
public IActionResult Edit(int id,MusicViewModel model)
{
var album = _musicData.GetM(id);
if (album != null && ModelState.IsValid)
{
album.Album = model.Album;
album.Artist = model.Artist;
album.Label = model.Label;
album.Review = model.Review;
album.ReleaseDate = model.ReleaseDate;
_musicData.RemoveOptions(id);
foreach (Types type in model.Options)
{
var opt = new Options();
opt.MusicID = id;
opt.Types = type;
_musicData.AddOptions(opt);
}
_musicData.Commit();
return RedirectToAction("Details",id);
}
return View(album);
}

Related

Asp.net core 6 get value from drop downlist

I am using the #Html.dropdownlistfor that allows the user to choose the customer that creates the deal. But the chhosed customer did not proceed to the controller which led to an unvalid model state. I got the reason that the model was not valid
but I did not know how to solve it. I have followed these links but the problem is still the same.
How do I get the Selected Value of a DropDownList in ASP.NET Core
MVC App
How to get DropDownList SelectedValue in Controller in MVC
SelectList from ViewModel from repository Asp.net core
Sorry if my question is naive I am new to ASP.net core MVC.
the code is as below:
namespace MyShop.ViewModels
{
public class CreateDealVM
{
public Deals deal { get; set; }
public IEnumerable<SelectListItem> CustomerListVM { get; set; }
}
}
The Model class:
namespace MyShop.Models
{
[Table("Deals")]
public class Deals
{
[Key]
[Display(Name = "ID")]
public int dealId { get; set; }
[ForeignKey("Customer")]
[Display(Name = "Customer")]
public Customer customer { get; set; }
[Display(Name = "CustomerName")]
public string? parentCustomerName { get; set; }
[Display(Name = "product")]
public DealTypeEnum product { get; set; }
[Display(Name = "Date")]
public DateTime saleDate { get; set; }
[Display(Name = "Quantity")]
public float quantity { get; set; }
[Display(Name = "Price")]
public float price { get; set; }
}
The Controller:
public IActionResult Create()
{
CreateDealVM vm = new CreateDealVM();
vm.CustomerListVM = _context.Customers.Select(x => new SelectListItem { Value = x.customerId.ToString(), Text = x.customerName }).ToList();
return View(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind("dealId,customer,product,saleDate,quantity,price")] Deals deal, CreateDealVM vm)
{
if (ModelState.IsValid)
{
try
{
vm.deal.customer = _context.Customers.Find(vm.CustomerListVM);
vm.deal = deal;
_context.Deals.Add(vm.deal);
_context.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return View(vm);
}
else
{
var errors = ModelState.Select(x => x.Value.Errors)
.Where(y => y.Count > 0)
.ToList();
//The Error showed here.
}
return View(vm);
}
The view:
#model MyShop.ViewModels.CreateDealVM
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Deals</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">
#Html.LabelFor(model => model.deal.customer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CustomerListVM,Model.CustomerListVM,"Select Customer", htmlAttributes: new { #class = "form-control"})
</div>
</div>
<div class="form-group">
<label asp-for="deal.product" class="control-label"></label>
<select asp-for="deal.product" class="form-control"></select>
<span asp-validation-for="deal.product" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="deal.saleDate" class="control-label"></label>
<input asp-for="deal.saleDate" class="form-control" />
<span asp-validation-for="deal.saleDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="deal.quantity" class="control-label"></label>
<input asp-for="deal.quantity" class="form-control" />
<span asp-validation-for="deal.quantity" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="deal.price" class="control-label"></label>
<input asp-for="deal.price" class="form-control" />
<span asp-validation-for="deal.price" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
I just realise your Model is wrong
[Table("Deals")]
public class Deals
{
[Key]
[Display(Name = "ID")]
public int dealId { get; set; }
[ForeignKey("Customer")]
[Display(Name = "Customer")]
public int CustomerId { get; set; }
[Display(Name = "CustomerName")]
public string? parentCustomerName { get; set; }
[Display(Name = "product")]
public DealTypeEnum product { get; set; }
[Display(Name = "Date")]
public DateTime saleDate { get; set; }
[Display(Name = "Quantity")]
public float quantity { get; set; }
[Display(Name = "Price")]
public float price { get; set; }
public virtual Customer Customer { get; set; }
Change the Dropdown
<div class="col-md-10">
#Html.DropDownListFor(model => model.Deal.CustomerId,Model.CustomerListVM,"Select Customer", htmlAttributes: new { #class = "form-control"})
</div>
one more thing since you have created viewmodel for deal. You only need to do this on your Post Controller
public IActionResult Create()
{
CreateDealVM vm = new CreateDealVM();
vm.CustomerListVM = new SelectList (_context.Customers select new { Id = x.customerId.ToString(), Text = x.customerName }),
"Id","Text");
return View(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Deals deal)
{
CreateDealVM vm = new CreateDealVM();
vm.deal = deal;
vm.CustomerListVM = new SelectList (_context.Customers select new { Id = x.customerId.ToString(), Text = x.customerName }),
"Id","Text",VM.CustomerId);
if (ModelState.IsValid)
{
try
{
_context.Deals.Add(vm.deal);
_context.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return View(vm);
}
else
{
var errors = ModelState.Select(x => x.Value.Errors)
.Where(y => y.Count > 0)
.ToList();
//The Error showed here.
}
return View(vm);
}

Creating a comment-like box in ASP.NET Core

I'm trying to create a comment and like box like the one shown in this tutorial what are the main changes I need to make in order to make it work with ASP.NET Core 3.1
https://www.c-sharpcorner.com/blogs/how-to-create-a-comment-box-session-as-like-facebook-comment-in-asp-net
To create a Facebook-like comment box in ASP.NET Coreļ¼Œ I do a demo to make it, referring to official documentation to configure database:https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-5.0&tabs=visual-studio
1.To Create the comment box, we need to create User, Reply, Comment models to add some tables ,and add some ViewModels.
User.cs:
public class User
{
[Key]
public int Id { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string Email { get; set; }
public string ImageUrl { get; set; }
public DateTime? CreateOn { get; set; }
}
Reply.cs:
public class Reply
{
[Key]
public int Id { get; set; }
[Required]
public string Text { get; set; }
public DateTime? CreateOn { get; set; }
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual User User { get; set; }
public int CommentId { get; set; }
[ForeignKey("CommentId")]
public virtual Comment Comment{get;set;}
}
Comment.cs:
public class Comment
{
[Key]
public int Id { get; set; }
[Required]
public string Text { get; set; }
public DateTime? CreateOn { get; set; }
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual User User { get; set; }
public ICollection<Reply> Replies { get; set; }
public ICollection<User> Users { get; set; }
}
LoginVM.cs:
public class LoginVM
{
[Required]
[Key]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
}
RegisterVM.cs:
public class RegisterVM
{
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
[Compare("Password")]
public string ConfirmPassword { get; set; }
[Required]
public string Email { get; set; }
}
ReplyVM.cs:
public class ReplyVM
{
public string Reply { get; set; }
public int CID { get; set; }
}
Installs the EF Core package
From the Tools menu, select NuGet Package Manager > Manage NuGet Packages for solution.
[Note]My core3.1 installed 3.1.21 version
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.SqlServer.Design
Microsoft.EntityFrameworkCore.Proxies
Microsoft.Extensions.Configuration.JSON
creates a database context class: Models/ApplicationDbContext.cs
public class ApplicationDbContext: DbContext
{
public ApplicationDbContext(DbContextOptions options) :base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Reply> Replies { get; set; }
public DbSet<commentbox.ViewModels.LoginVM> LoginVM { get; set; }
}
4.Add codes in Startup.ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddSession();
services.AddControllersWithViews();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ApplicationDbContext")));
}
5.Add app.UseSession(); in Startup.Configure
6.Add a connection string to the appsettings.json file:
"ConnectionStrings": {
"ApplicationDbContext": "Server=(localdb)\\mssqllocaldb;Database=ApplicationDbContext-1;Trusted_Connection=True;MultipleActiveResultSets=true"}
7.In the Package Manager Console (PMC), enter the following commands separately:
Add-Migration InitialCreate
Update-Database
8.Add HomeController to set userId=0 when people first Login without register, add AccountController to manage user login or not, add ChatRoomController to manage user post comments or reply.
HomeController.cs:
public class HomeController : Controller
{ ....
public IActionResult Index()
{
ISession session = HttpContext.Session;
session.SetInt32("UserId", 0);
return View();
}
...
}
AccountController.cs:
public class AccountController : Controller
{
private readonly ApplicationDbContext db;
public AccountController(ApplicationDbContext context)
{
db = context;
}
//GET:Account/Register
[HttpGet]
public IActionResult Register()
{
return View();
}
//GET:Account/Register
[HttpPost]
public IActionResult Register(RegisterVM obj)
{
bool UserExistis=db.Users.Any(x=>x.UserName==obj.UserName);
if(UserExistis)
{
ViewBag.UserNameMessage = "This UserName is already in use, try another";
return View();
}
bool EmailExistis = db.Users.Any(y => y.Email == obj.Email);
if (EmailExistis)
{
ViewBag.EmailMessage = "This Email is already in use, try another";
return View();
}
//if username and email is unique, then we save or register the user
User u = new User();
u.UserName = obj.UserName;
u.Password = obj.Password;
u.Email = obj.Email;
u.ImageUrl = "";
u.CreateOn = DateTime.Now;
db.Users.Add(u);
db.SaveChanges();
return RedirectToAction("Index","ChatRoom");
}
//GET:Account/Login
[HttpGet]
public IActionResult Login()
{
return View();
}
//GET:Account/Login
[HttpPost]
public IActionResult Login(LoginVM obj)
{
bool existis = db.Users.Any(u => u.UserName == obj.UserName&&u.Password==obj.Password);
if(existis)
{
ISession session = HttpContext.Session;
session.SetInt32("UserId", db.Users.Single(x => x.UserName == obj.UserName).Id);
return RedirectToAction("Index","ChatRoom");
}
//if invalid credentials
ViewBag.Message = "Invalid Credentials!";
return View();
}
}
ChatRoomController.cs:
public class ChatRoomController: Controller
{
private readonly ApplicationDbContext db;
public ChatRoomController(ApplicationDbContext context)
{
db = context;
}
public IActionResult Index()
{
var comments = db.Comments.Include(x => x.Replies).ThenInclude(x=>x.User).OrderByDescending(x => x.CreateOn)
.ToList();
return View(comments);
}
//Post:ChatRoom/PostReply
[HttpPost]
public ActionResult PostReply(ReplyVM obj)
{
ISession session = HttpContext.Session;
int userId =(int)session.GetInt32("UserId");
if (userId==0)
{
return RedirectToAction("Login", "Account");
}
Reply r = new Reply();
r.Text = obj.Reply;
r.CommentId = obj.CID;
r.UserId =userId;
r.CreateOn = DateTime.Now;
db.Replies.Add(r);
db.SaveChanges();
return RedirectToAction("Index");
}
//Post:ChatRoom/PostComment
[HttpPost]
public ActionResult PostComment(string CommentText)
{
ISession session = HttpContext.Session;
int userId = (int)session.GetInt32("UserId");
if (userId == 0)
{
return RedirectToAction("Login", "Account");
}
Comment c = new Comment();
c.Text = CommentText;
c.CreateOn = DateTime.Now;
c.UserId = userId;
db.Comments.Add(c);
db.SaveChanges();
return RedirectToAction("Index");
}
}
9.Add views: Login.cshtml(for Login action in AccountController), Register.cshtml(for Register action in AccountController), index.cshtml(for Index action in ChatRoomController).
Login.cshtml:
#model commentbox.ViewModels.LoginVM
#{
ViewData["Title"] = "Login";
}
<h1>Login</h1>
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-4">
<form asp-action="Login">
<h4 class="text-danger">#ViewBag.Message</h4>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="UserName" class="control-label"></label>
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</form>
</div>
</div>
Register.cshtml:
#model commentbox.ViewModels.RegisterVM
#{
ViewData["Title"] = "Register";
}
<h1 class="text-success">Register User</h1>
<div class="row">
<div class="col-md-4">
<form asp-action="Register">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="UserName" class="control-label"></label>
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
<p class="text-danger">#ViewBag.UserNameMessage </p>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ConfirmPassword" class="control-label"></label>
<input asp-for="ConfirmPassword" class="form-control" />
<span asp-validation-for="ConfirmPassword" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
<p class="text-danger">#ViewBag.EmailMessage </p>
</div>
<div class="form-group">
<input type="submit" value="Register" class="btn btn-primary" style="border-radius:20px"/>
</div>
</form>
</div>
</div>
Index.cshtml:
#model IEnumerable<commentbox.Models.Comment>
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<h2 class="text-success text-center"> someone's post or some other things</h2>
#using (Html.BeginForm("PostComment", "ChatRoom", FormMethod.Post))
{
<input type="text" name="CommentText" placeholder="Type new comment..."
style="width:700px; height:60px; font-size:20px; margin-top:10px" />
<br />
<input type="submit" value="Post Comment" class="btn btn-success "
style="margin-top: 10px;margin-bottom: 10px " />
}
<table class="table text-center">
<tbody>
#foreach (var comment in Model)
{
<tr style="border:1px solid black;">
<td>
<span style="margin-right:15px;font-size:16px;color:green">
#Html.DisplayFor(modelItem => comment.User.UserName)
</span>
<span style="font-size:20px">
#Html.DisplayFor(modelItem => comment.Text)
</span>
<span style="margin-left:10px">
#Html.DisplayFor(modelItem => comment.CreateOn)
</span>
#foreach (var reply in comment.Replies)
{
<br />
<span style="margin-right:15px;font-size:16px;color:blue">
#Html.DisplayFor(modelItem => reply.User.UserName)
</span>
<span style="font-size:19px">
#reply.Text
</span>
<span style="margin-left:10px">
#reply.CreateOn
</span>
}
<br />
#using (Html.BeginForm("PostReply", "ChatRoom", FormMethod.Post))
{<input type="text" name="Reply" placeholder="Type reply..."
style="width:100%; height:60px; font-size:20px; margin-top:10px" />
<br />
<input type="hidden" name="CID" value="#comment.Id" />
<input type="submit" value="Post Reply" class="btn btn-success" style="margin-top :10px" />
}
</td>
</tr>
}
</tbody>
</table>
10.Add link in _Layout.cshtml.
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Account" asp-action="Register">Register</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Account" asp-action="Login">Login</a>
</li>

handling form in controller using viewmodel with two parameters

I want to save values from a form to my database. I'm using a viewmodel with an selectlist property and a regular model. The value from the dropdown doesn't get saved. Despite being a trivial and seemingly pretty simple thing, I'm pretty lost.
Below my code:
Model:
public class Movie
{
public int MovieID { get; set; }
public string Name { get; set; }
public int StudioID { get; set; }
public Studio Studio { get; set; }
}
My ViewModel:
public class CreateMoviesViewModel
{
public Movie Movie { get; set; }
public IEnumerable<SelectListItem> StudiosSelectList { get; set; }
}
My Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CreateMoviesViewModel movieViewModel)
{
if (ModelState.IsValid)
{
_context.Add(movieViewModel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
movieViewModel.StudiosSelectList = new SelectList(_context.Studios.AsNoTracking(), "StudioID", "Name");
return View(movieViewModel);
And finally, my Form:
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Movie.MovieID" />
<div class="form-group">
<label asp-for="Movie.Name" class="control-label"></label>
<input asp-for="Movie.Name" class="form-control" />
<span asp-validation-for="Movie.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Movie.StudioID" class="control-label"></label>
#Html.DropDownListFor(m => m.StudiosSelectList, Model.StudiosSelectList, "Select one")
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
It is probably something wrong with my dropdown list, or with the logic described in the POST section. Any help is greatly appreciated!
You need to pass the selected dropdown value to your model:
public class CreateMoviesViewModel
{
public int SelectedValueId { get; set; } // <-- not sure what are you selecting, this could be MovieId if you are selecting a movie
public Movie Movie { get; set; }
public IEnumerable<SelectListItem> StudiosSelectList { get; set; }
}
Then you can use:
#Html.DropDownListFor(m => m.SelectedValueId, m.StudiosSelectList)
This way, the selected value Id would be passed to your model.
SelectValueId should be initialized to the default value that you want to display in the Dropdown.

How to create a view with the addition of related entities?

I have project with ASP.Net Core MVC, EF Core 2.0. There is a Person and Phone entity with a "one-to-many" relationship, i.e. each Person entity can contain many phones or none. When generating a standard controller, a view was also generated. The problem is that when creating the Person entity, the user should be able to add a phone, one or more. Many-day google did not give anything, probably because I do not know how to designate this in the search.
How to create a view with the ability to dynamically add related entities? In other words, how to create and add programmatically to the ICollection<Phone> Phone collection new Phone entities?
Model:
public partial class Person {
public Person() {
Phone = new HashSet<Phone>();
}
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Phone> Phone { get; set; }
}
}
public partial class Phone {
public int Id { get; set; }
public int Type { get; set; }
public int Number { get; set; }
public int? PersonId { get; set; }
public Person Person { get; set; }
}
public partial class ModelContext : DbContext {
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<Person>(entity => {
entity.Property(e => e.Name).HasMaxLength(50).IsRequired();
});
modelBuilder.Entity<Phone>(entity => {
entity.HasOne(d => d.Person)
.WithMany(p => p.Phone)
.HasForeignKey(d => d.PersonId)
.HasConstraintName("FK_Phone_Person");
});
}
}
Generated View:
#model xxx.Models.Person
#{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<h4>Person</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="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

MVC Subitem list

I am trying to create an entity that has subitems and am having issues with passing the model back and forth.
I have an entity RiskAssessnent that contains a list of Risk entities.
public class RiskAssessment
{
public int Id { get; set; }
public DateTime Date { get; set; }
public ICollection<Risk> Risks { get; set; }
public int ResidentId { get; set; }
public Resident Resident { get; set; }
public int EmployeeId { get; set; }
public Employee Employee { get; set; }
}
public class Risk
{
public int Id { get; set; }
public string Description { get; set; }
public int RiskAssessmentId { get; set; }
public RiskAssessment RiskAssessment { get; set; }
}
here is my view for creating a RiskAssessment:
#model CareHomeMvc6.Models.RiskAssessmentViewModels.RiskAssessmentViewModel
#{
ViewData["Title"] = "Create";
}
<a class="btn btn-default" asp-action="Index" asp-route-residentId="#Model.ResidentId">Back to List</a>
<div class="page-header">
<h1>Create a Risk Assessment</h1>
</div>
<form asp-action="Create">
<div class="form-horizontal">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
#Html.HiddenFor(m => m.EmployeeId)
#Html.HiddenFor(m => m.ResidentId)
<div class="form-group">
<label asp-for="Date" class="col-md-2 control-label"></label>
<div class="col-md-10">
#Html.EditorFor(m => m.Date, new { #class = "form-control" })
<span asp-validation-for="Date" class="text-danger" />
</div>
</div>
#foreach(var risk in Model.Risks)
{
<h3>#risk.Description</h3>
}
<p>
<a class="btn btn-success" asp-action="CreateRisk">Create</a>
</p>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
and here is the controller:
public IActionResult CreateRisk(RiskAssessmentViewModel riskAssessmentViewModel)
{
var vm = new CreateRiskViewModel
{
RiskAssessment = riskAssessmentViewModel,
Risk = new Risk()
};
return View(vm);
}
and the ViewModel:
public class RiskAssessmentViewModel
{
public RiskAssessmentViewModel()
{
this.Risks = new List<Risk>();
this.Risks.Add(new Risk
{
Id = 1,
Description = "blah",
PotentialRisk = "blah"
});
}
public int Id { get; set; }
[Display(Name = "Date")]
[DataType(DataType.Date)]
[Required]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
public ICollection<Risk> Risks { get; set; }
public int ResidentId { get; set; }
public int EmployeeId { get; set; }
}
Sorry for all the code so far!
I was attempting to keep passing the ViewModel back and forth until all items have been created but within the CreateRisk action the ResidentId and EmployeeId are 0 therefore not being set, although I do get the collection of risks. If I click submit on the form which encapsulates everything then they are set. Is there any reason the hidden items are being sent to the form submit but not the link action?
I realise there are JS solutions to doing dynamic lists but I wanted to stay away from it as the page navigation is acceptable, the form will when finished require a lot of data entry for a Risk.
Any help with this would be greatly appreciated.
Thanks

Resources