Automatically select the options of multiple selection drop down for the edit page in ASP.NET Core 6.0 Razor Pages - c#

I am beginner in ASP.NET Core. I need help with automatically selecting the options of a multi-selection dropdown.
I have a class model and a class can have multiple students. When I am creating the class, I have a dropdown that shows the student list and I can add the students to the class by selecting the options form the drop down.
But I am having issues automatically selecting those values for the edit page. The dropdown should keep those students selected from the list when the edit page loads so that the user can see which students are currently enrolled in the class. I am only seeing the students that are enrolled in the class as option of the dropdown. It should show all the students in the list but select the ones that belongs to the class.
My class model:
public class ClassModel
{
[Key]
[Required]
[Display(Name ="Class ID")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ClassID { get; set; }
//[ForeignKey("UserProfile")]
//[Display(Name = "User ID")]
//public virtual int ID { get; set; }
[Required]
public string Description { get; set; }
[Required]
public int Occurence { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime Startdate { get; set; }
[Required]
[DataType(DataType.Time)]
public DateTime From { get; set; }
[Required]
[DataType(DataType.Time)]
//[GreaterThanOrEqualTo("From")]
public DateTime To { get; set; }
[Required]
[DataType(DataType.Currency)]
public double Fees { get; set; }
[DisplayFormat(NullDisplayText = "No Instructor Assigned")]
[ForeignKey("InstructorID")]
public virtual int InstructorID { get; set; }
public Instructor? Instructor { get; set; }
// [DisplayFormat(NullDisplayText = "No Student Assigned")]
[NotMapped]
public ICollection<int> StudentID { get; set; }
public ICollection<Enrollment>? Enrollment { get; set; }
}
EditClass.cshtml.cs code:
public class EditModel : PageModel
{
private readonly TestProject.Data.TestProjectContext _context;
public EditModel(TestProject.Data.TestProjectContext context)
{
_context = context;
}
[BindProperty]
public Model.ClassModel Class_Info { get; set; }
[BindProperty]
public ClassModelStudent Class_Student { get; set; }
public Model.Instructor instructor { get; set; }
public SelectList Instructors { get; set; }
public SelectList Students { get; set; }
public MultiSelectList Class_Student { get; set; }
public SelectList SelectedStudents { get; set; }
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null)
{
return NotFound();
}
Class_Info = await _context.Class.FirstOrDefaultAsync(m => m.ClassID == id);
var instructors = from i in _context.Instructor
orderby i.FirstName
select i;
Instructors = new SelectList(instructors, "InstructorID", "FirstName");
var selectedstudents = from cs in _context.ClassModelStudent
join s in _context.User_Profile on cs.StudentsStudentID equals s.StudentID
select new { cs.StudentsStudentID, s.FullName, s.PhoneNumber };
SelectedStudents = new SelectList(selectedstudents, "StudentsStudentID", "FullName");
Class_Student = SelectedStudents;
var students = from cs in _context.ClassModelStudent
join s in _context.User_Profile on cs.StudentsStudentID equals s.StudentID
select new { cs.StudentsStudentID, s.FullName, s.PhoneNumber };
Students = new SelectList(students, "StudentsStudentID", "FullName", "PhoneNumber");
// Class_Student.StudentsStudentID = id;
//from s in _context.ClassModelStudent
// orderby s.StudentsStudentID
// select s;
if (Class_Info == null)
{
return NotFound();
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Attach(Class_Info).State = EntityState.Modified;
_context.Attach(Class_Student).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!Class_InfoExists(Class_Info.ClassID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToPage("./Index");
}
private bool Class_InfoExists(int id)
{
return _context.Class.Any(e => e.ClassID == id);
}
}
EditClass.cshtml view markup:
#page
#model TestProject.Pages.Classes.EditModel
#{
ViewData["Title"] = "Edit";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<h1>Edit</h1>
<h4>Class_Info</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Class_Info.ClassID" />
#*<div class="form-group">
<label asp-for="Class_Info.ID" class="control-label"></label>
<input asp-for="Class_Info.ID" class="form-control" />
<span asp-validation-for="Class_Info.ID" class="text-danger"></span>
</div>*#
<div class="form-group">
<label asp-for="Class_Info.Description" class="control-label"></label>
<input asp-for="Class_Info.Description" class="form-control" />
<span asp-validation-for="Class_Info.Description" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Class_Info.Occurence" class="control-label"></label>
<input asp-for="Class_Info.Occurence" class="form-control" />
<span asp-validation-for="Class_Info.Occurence" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Class_Info.Startdate" class="control-label"></label>
<input asp-for="Class_Info.Startdate" class="form-control" />
<span asp-validation-for="Class_Info.Startdate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Class_Info.From" class="control-label"></label>
<input asp-for="Class_Info.From" class="form-control" />
<span asp-validation-for="Class_Info.From" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Class_Info.To" class="control-label"></label>
<input asp-for="Class_Info.To" class="form-control" />
<span asp-validation-for="Class_Info.To" class="text-danger"></span>
</div>
<div class="form-group">
#* <label asp-for="instructor.FirstName" class="control-label"></label>
<input asp-for="instructor.FirstName" class="form-control" />*#
<label asp-for="Class_Info.InstructorID" class="control-label"></label>
<select asp-for="Class_Info.InstructorID" class="form-control" asp-items="#Model.Instructors">
<option value="">-- Select --</option>
</select>
<span asp-validation-for="Class_Info.InstructorID" class="text-danger"></span>
</div>
<div class="form-group">
#* <label asp-for="instructor.FirstName" class="control-label"></label>
<input asp-for="instructor.FirstName" class="form-control" />*#
-- Select --
<div>
<a asp-page="./Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Please advise. I would really appreciate your help.

Related

displaying the input box for a different model

I have following two model classes:
public partial class EmployeeInfo
{
public string LastName { get; set; } = null!;
public string FirstName { get; set; } = null!;
public virtual ICollection<EmergencyInfo> EmergencyInfos { get; } = new List<EmergencyInfo>();
}
public partial class EmergencyInfo
{
public string emailAddress { get; set; } = null!;
public string PhoneNumber { get; set; } = null!;
public virtual EmployeeInfo EmployeeInfo { get; set; } = null!;
}
My Razor view to create a new employee looks like this:
#model AckPackage.Models.EmployeeInfo
#{
ViewData["Title"] = "Create";
}
<div class="form-group row">
<div class="col-sm-4">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control input-lg" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="col-sm-4">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control input-lg" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
</div>
Can I display the input box for emeregencyInfo, emailAddress and phone number in above view. I want to show both the input box for emailAddress and PhoneNumber in the same EmployeeInfo view so that users can input their information.
Any help will be highly appreciated.
You can create a compound class and pass it to the view as data model:
public class Info
{
public EmployeeInfo? Employee { get; set; }
public EmergencyInfo? Emergency { get; set; }
}
The view code:
#model Info;
#{
ViewData["Title"] = "Create";
}
<form method="post" asp-action="Create">
<div class="form-group row">
<div class="col-sm-4">
<label asp-for="#Model.Employee.LastName" class="control-label"></label>
<input asp-for="#Model.Employee.LastName" class="form-control input-lg" />
<span asp-validation-for="#Model.Employee.LastName" class="text-danger"></span>
</div>
...
<button type="submit">Save</button>
</form
On the controller side:
[HttpPost]
public IActionResult Create(Info data)
{
// Processing the entered data
....
return View(data);
}

ModelState Invalid on form submit - IEnumerable<SelectListItem> is required

I have a form that adds a branch, the form has a drop down to select the company name.
I created a viewModel that has the SelectListItem of the companies and the Branch Model
When submit a form, modelState.IsValid equals to false.
reason for that is because CompaniesList is required.
any idea why is it required? how can i overcome this?
Branch model:
public class Branch
{
public int Id { get; set; }
public int CompanyId { get; set; }
[MaxLength(50)]
public string? City { get; set; }
[MaxLength(50)]
public string? BranchName { get; set; }
public DateTime CreatedAt { get; set; }
[MaxLength(100)]
public string? CreatedBy { get; set; }
}
ViewModel:
public class BranchVM
{
public Branch branch { get; set; }
[AllowNull]
public IEnumerable<SelectListItem> CompaniesList { get; set; }
}
Create.cshtml:
#model Click2Lock.Models.BranchVM
<form method="post" enctype="multipart/form-data">
<div class="border p-3 mt-4">
<div class="row pb-2">
<h2 class="text-primary">Create Branch</h2>
<hr/>
</div>
<div class="col-8">
<label asp-for="branch.BranchName">Branch Name</label>
<input asp-for="branch.BranchName" class="form-control"/>
<span asp-validation-for="branch.BranchName" class="text-danger"></span>
</div>
<div class="col-8">
<label asp-for="branch.City">City</label>
<input asp-for="branch.City" class="form-control"/>
<span asp-validation-for="branch.City" class="text-danger"></span>
</div>
<div class="col-8 pb-4">
<div class="form-group row">
<div class="col-4">
<label asp-for="branch.CompanyId">Company</label>
</div>
<div class="col-8">
#Html.DropDownListFor(m => m.branch.CompanyId, Model.CompaniesList , "Select Order",
new { #class = "form-control" })
<span asp-validation-for="branch.CompanyId" class="text-danger"></span>
</div>
</div>
</div>
<div class="col-8">
<input type="hidden" asp-for="branch.CreatedAt" class="form-control" value="#DateTime.Now" />
</div>
<div class="col-8">
<input type="hidden" asp-for="branch.CreatedBy" class="form-control" value=#ViewBag.userName />
</div>
<button type="submit" class="btn btn-primary" style="width:200px">Add New Branch</button>
<a asp-controller="Company" asp-action="Index" class="btn btn-secondary" style="width:150px">
Back To List
</a>
</div>
</form>
create on Controller :
public IActionResult Create()
{
ViewBag.userName = (_unitOfWork.ApplicationUser.GetAll().
Where(q => q.UserName == User.Identity.Name).Select(q => q.FullName)).FirstOrDefault();
BranchVM branchVM = new BranchVM()
{
branch = new Branch(),
CompaniesList = _unitOfWork.Company.GetAll().OrderBy(a=>a.CompanyName).
Select(i => new SelectListItem
{
Text = i.CompanyName,
Value = i.Id.ToString()
})
};
return View(branchVM);
}
//POST
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(BranchVM branchVM)
{
ViewBag.msgCreate = 0;
ViewBag.msgGeneralException = 0;
if (ModelState.IsValid)
{
try
{
_unitOfWork.Branch.Add(branchVM.branch);
_unitOfWork.Save();
ViewBag.msgCreate = 1;
return View(branchVM);
}
catch (Exception ex)
{
ViewBag.msgGeneralException = 1;
return View(branchVM);
}
}
ViewBag.msgGeneralException = 1;
return View(branchVM);
}
One technique is to make it nullable:
public IEnumerable<SelectListItem>? CompaniesList { get; set; }

How to populate dropdown list from nested Models? (Asp.net Core MVC)

I have a nested model and I use one model named (BootstrapTool) to make the view strongly typed.
I use ViewBag to populate a dropdown list with the nested Model named (BootstrapCategory). But my problem is when I select from it always returns validation null exception.
BootstrapTool Model
public class BootstrapTool
{
public Guid Id { get; set; }
[MaxLength(100,ErrorMessage ="Max 100")]
[Required]
public string tool { get; set; }
[MaxLength(300, ErrorMessage = "Max 300")]
[Required]
public string descreption { get; set; }
[Required]
public string html { get; set; }
[Required] // here where nisting the other Model BootstrapCategory
public BootstrapCategory category { get; set; }
}
BootstrapCategory Model
public class BootstrapCategory
{
[Key]
public Guid Id { get; set; }
[MaxLength(20)]
[Required]
public string Category { get; set; }
}
The Controller
public IActionResult Create()
{
List<BootstrapCategory> bootstrapCategories = _context.bootstrapCategories.ToList();
ViewBag.bpCategories = new SelectList(bootstrapCategories, "Id", "Category");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(BootstrapTool bootstrapTool)
{
if (ModelState.IsValid)
{
bootstrapTool.Id = Guid.NewGuid();
_context.Add(bootstrapTool);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(bootstrapTool);
}
Here where the dropdown list is to display BootstrapCategory
The View
#model BootstrapTool
<div class="row">
<div class="col-10 offset-1">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="gap-2 d-flex justify-content-between">
<div class="form-group w-50">
<label asp-for="tool" class="control-label"></label>
<input asp-for="tool" class="form-control" />
<span asp-validation-for="tool" class="text-danger"></span>
</div>
<div class="form-group w-50">
<label class="control-label">category</label>
<select asp-for="category.Id" class="form-control" asp-items="#ViewBag.bpCategories">
<option value="" disabled hidden selected>Select Section ...</option>
</select>
<span asp-validation-for="category" class="text-danger"></span>
#*<select asp-for="Id" asp-items="#Html.GetEnumSelectList<Enum>()" class="form-control">
<option value="" hidden disabled selected> -- please selecgt -- </option>
</select>*#
</div>
</div>
<div class="form-group">
<label asp-for="descreption" class="control-label"></label>
<textarea asp-for="descreption" class="form-control" rows="2"></textarea>
<span asp-validation-for="descreption" class="text-danger"></span>
</div>
<div class="form-group mb-2">
<label asp-for="html" class="control-label"></label>
<textarea asp-for="html" class="form-control" rows="5"></textarea>
<span asp-validation-for="html" class="text-danger"></span>
</div>
<div class="form-group mt-3">
<input type="submit" value="Create" class="btn btn-primary d-grid col-6 mx-auto" />
</div>
</form>
</div>
</div>
Add CategoryId
public class BootstrapTool
{
[Key]
public Guid Id { get; set; }
[Required]
public Guid? CategoryId { get; set; }
[ForeignKey(nameof(CategoryId))]
[InverseProperty("BootstrapTools")]
public BootstrapCategory Category { get; set; }
}
public class BootstrapCategory
{
[Key]
public Guid Id { get; set; }
[MaxLength(20)]
[Required]
public string Category { get; set; }
[InverseProperty(nameof(BootstrapTool.Category))]
public virtual ICollection<BootstrapTool> BootstrapTools { get; set; }
}
and fix the view
<select asp-for="CategoryId" class="form-control" asp-items="#ViewBag.bpCategories">
</select>
```

CRUD with Many to Many relationships in Entity Framework Core

I have two models and one join table.
I would like to use the same view to edit and create new purchase order while adding items in the same form.
PurchaseOrder Model:
public class PurchaseOrder
{
public int ID { get; set; }
[Required]
public string Requester { get; set; }
public int WorkOrder { get; set; }
[Required]
public string WorkSite { get; set; }
public string Equipment { get; set; }
public string Operator { get; set; }
public string Remarks { get; set; }
public ICollection<PurchaseOrderItem> Items { get; set; }
}
Item Model:
public class Item
{
public int ID { get; set; }
public string PartNumber { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
[Required]
public int Quantity { get; set; }
public string Remarks { get; set; }
public ICollection<PurchaseOrderItem> PurchaseOrders { get; set; }
}
Join Table Entity
public class PurchaseOrderItem
{
public int PurchaseOrderID { get; set; }
public int ItemID { get; set; }
public PurchaseOrder PurchaseOrder { get; set; }
public Item Item { get; set; }
}
PurchaseOrdersController Edit:
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var purchaseOrder = await _context.PurchaseOrders
.Include(x => x.Items)
.ThenInclude(x => x.Item)
.Where(x => x.ID == id)
.AsNoTracking()
.SingleOrDefaultAsync();
if (purchaseOrder == null)
{
return NotFound();
}
return View(purchaseOrder);
}
Edit Post Method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, PurchaseOrder order)
{
if (id != order.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
var po = _context.PurchaseOrders.FirstOrDefault(i => i.ID == order.ID);
po.Requester = order.Requester;
po.WorkOrder = order.WorkOrder;
po.WorkSite = order.WorkSite;
po.Equipment = order.Equipment;
po.Operator = order.Operator;
po.Remarks = order.Remarks;
_context.Update(po);
foreach (var i in order.Items)
{
var item = _context.Items.FirstOrDefault(n => n.ID == i.Item.ID);
item.PartNumber = i.Item.PartNumber;
item.Name = i.Item.Name;
item.Description = i.Item.Description;
item.Quantity = i.Item.Quantity;
item.Remarks = i.Item.Remarks;
_context.Update(item);
}
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PurchaseOrderExists(order.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(order);
}
Edit View
#model OrderTrackingApp.Models.PurchaseOrder
#{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>PurchaseOrder</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ID" />
<div class="form-group">
<label asp-for="Requester" class="control-label"></label>
<input asp-for="Requester" class="form-control" />
<span asp-validation-for="Requester" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="WorkOrder" class="control-label"></label>
<input asp-for="WorkOrder" class="form-control" />
<span asp-validation-for="WorkOrder" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="WorkSite" class="control-label"></label>
<input asp-for="WorkSite" class="form-control" />
<span asp-validation-for="WorkSite" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Equipment" class="control-label"></label>
<input asp-for="Equipment" class="form-control" />
<span asp-validation-for="Equipment" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Operator" class="control-label"></label>
<input asp-for="Operator" class="form-control" />
<span asp-validation-for="Operator" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Remarks" class="control-label"></label>
<input asp-for="Remarks" class="form-control" />
<span asp-validation-for="Remarks" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Order Items</label>
<table>
<tbody>
#{ int i = 0;}
<tr>
#foreach (var OrderItem in Model.Items)
{
<td>
<input type="hidden" value="OrderItem[#i].ItemID" asp-for="#OrderItem.ItemID"
class="form-control" />
<input type="text" value="OrderItem[#i].Item.PartNumber" asp-for="#OrderItem.Item.PartNumber" class="form-control" />
<input type="text" value="OrderItem[#i].Item.Name" asp-for="#OrderItem.Item.Name" />
</td>
i++;
}
</tr>
</tbody>
</table>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
I have two problems currently with the Edit:
The label for the item populates as follows: OrderItem[0].Item.Name instead of Value
When the code reaches the foreachloop to iterate over items, it is throwing a null exception.
You are getting name only as for newly added child items, you don't have ids. and getting null values as in returned data for relational table ids of child data are not initialized.
you can solve this issue in tow ways as per suitability:
Add child rows from view directly and update ids in model, so you
will always have ids in data and you will not need face null ids
issue.
Alternatively, You may need to add new values of child table first
then use new ids in relational data manually before saving changes.
The problem is model binding, it is based on the name attribute. Change the code like below:
#{ int i = 0;}
<tr>
#foreach (var OrderItem in Model.Items)
{
<td>
<input type="hidden" name="Items[#i].Item.ID" asp-for="#OrderItem.Item.ID"
class="form-control" />
<input type="text" name="Items[#i].Item.PartNumber" asp-for="#OrderItem.Item.PartNumber" class="form-control" />
<input type="text" name="Items[#i].Item.Name" asp-for="#OrderItem.Item.Name" class="form-control" />
</td>
i++;
}
</tr>

How to use 2 Models in a View

How can I use Two different models into the same view?
Why I need this?
I need to do a create view where the client fills his registry, and I need to have 1 combo box/select form(This form needs to load the strings from the other model).
Here is what I have tried:
Creating a ViewModel for both of the Models that looks like this:
public class CandidateViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int Number { get; set; }
public string Profile { get; set; }
public Byte[] CV { get; set; }
public string CVNAME { get; set; }
public List<Profile> ProfileList { get; set; }
public string ProfileText { get; set; }
}
ProfileList and ProfileText are from ProfileModel, the rest is from the CandidateModel.
My controller right now looks like this:
public IActionResult Candidate(Candidate candidate, string searchString)
{
using (var aplicationDbContext = new ApplicationContext())
{
var candidates = from m in aplicationDbContext.Candidates select m;
if (!String.IsNullOrEmpty(searchString))
{
candidates = candidates.Where(s => s.Name.Contains(searchString) || s.Number.ToString().Contains(searchString) || s.ProfileText.Contains(searchString));
}
return View(candidates.ToList());
}
}
public IActionResult CandidateCreate()
{
using (var applicationcontext = new ApplicationContext())
{
var ProfileTextFromProfile = applicationcontext.Candidates.Include(q => q.ProfileList);
return View(ProfileTextFromProfile);
}
return View();
}
[HttpPost, ActionName("CandidateCreate")]
[ValidateAntiForgeryToken]
public IActionResult CandidateCreatePost([Bind("Name,Number,Profile,CV,CVID")] Candidate candidate, IFormFile CV,string profileText, int Id)
{
if (ModelState.IsValid)
{
if (CV != null)
{
if (CV.Length > 0)
{
byte[] p1 = null;
using (var fs1 = CV.OpenReadStream())
using (var ms1 = new MemoryStream())
{
fs1.CopyTo(ms1);
p1 = ms1.ToArray();
}
candidate.CVNAME = CV.FileName;
candidate.CV = p1;
}
}
using (var applicationcontext = new ApplicationContext())
{
var ProfileTextFromProfile = applicationcontext.Profile.Include(q => q.ProfileList);
//var ProfileTextFromProfile = applicationcontext.Profile.Include(q => q.ProfileText).Single(q => q.Id == Id);
//ProfileTextFromProfile.ProfileText.Add(new Candidate() { Profile = profileText });
}
candidateRepository.Add(candidate);
candidateRepository.SaveChanges();
return RedirectToAction("Candidate");
}
return View();
}
But I don't know what acctually I need to do after this, I'm really new to this and I'm doing this work as an intership soo I'm still learning, If have any doubts about my question please ask me and I will try to explain.
Also here is my View where I need to use both of the models.
#*model HCCBPOHR.Data.Candidate*#
#model HCCBPOHR.DomainModel.CandidateModel
#{
ViewData["Title"] = "CandidateCreate";
}
<h2>CandidateCreate</h2>
<h4>Candidate</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post" enctype="multipart/form-data" asp-action="CandidateCreate">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Number" class="control-label"></label>
<input asp-for="Number" class="form-control" maxlength="9" />
<span asp-validation-for="Number" class="text-danger"></span>
</div>
<div class="form-group">
<label>Selects</label>
<select asp-for="Profile" class=" form-control ">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<label asp-for="CV" type="file" class="control-label"></label>
<input asp-for="CV" type="file" class="form-control" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" onclick="this.disabled=true;this.form.submit();" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
You can apply MVVM pattern in this scenario.
Here is example:
I will define 3 class in Model folder
public class Post
{
public string Id {get;set;}
public string Content {get;set;}
public string UserId {get;set;}
}
public class Comment
{
public string Id {get;set;}
public string Content {get;set;}
public string PostId {get;set;}
}
// this will hold data for 2 class above
public class PostVM
{
public Post Post {get;set}
public Comment Comment {get;set}
}
Then in my controller I will query to db to get data for post and comment like this
public IActionResult PostDetail(string postId)
{
var post = _postRepository.GetPostById(postId);
var comment = _commentRepository.GetCommentByPostId(postId);
// MVVM model return to the view
var vM = new PostVM
{
Post = post,
Comment = comment
}
}
Finally in my view
#model PostVM
<div> #model.Post.Content </div>
#foreach(var comment in #model.Comment)
{
<div> #comment.Content</div>
}
Please adjust accordingly with your code. If you have any problem please let me know.
Cheers

Categories