Let's create a scenario where you have a NewInformationVm ViewModel to handle both creating new records and listing existing ones.
ViewModel
public class NewInformationVm
{
public int Id { get; set; }
public Person Person { get; set; }
public Student Student { get; set; }
public List<Item> Items { get; set; }
public NewInformationVm()
{
Person = new Person();
Student = new Student();
Items = new List<Item>();
}
}
public class Item
{
public int ItemId { get; set; }
public string ItemName { get; set; }
// other properties...
}
Controller
public class InformationController : Controller
{
private List<Item> GetItems()
{
// Logic to fetch or create items
return new List<Item>
{
new Item { ItemId = 1, ItemName = "Item 1" },
new Item { ItemId = 2, ItemName = "Item 2" }
// Add more items...
};
}
public IActionResult Create()
{
var viewModel = new NewInformationVm
{
Items = GetItems()
};
return View(viewModel);
}
[HttpPost]
public IActionResult Create(NewInformationVm model)
{
if (ModelState.IsValid)
{
// Save logic
// Add the new item to the Items collection for demonstration
model.Items.Add(new Item { ItemId = model.Items.Count + 1, ItemName = "New Item" });
return View(model);
}
return View(model);
}
}
Main View (Create. cshtml)
@model myprojectname.ViewModels.NewInformationVm
<h2>Create New Record</h2>
<form asp-action="Create" method="post">
<div>
<label>Person Name:</label>
<input asp-for="Person.Name" />
</div>
<div>
<label>Student Name:</label>
<input asp-for="Student.Name" />
</div>
<button type="submit">Create</button>
</form>
<h2>Item List</h2>
@Html.Partial("_ItemList", Model)
Partial View (_ItemList.cshtml)
@model myprojectname.ViewModels.NewInformationVm
@if (Model.Items != null && Model.Items.Any())
{
<ul>
@foreach (var item in Model.Items)
{
<li>@item.ItemName</li>
}
</ul>
}
else
{
<p>No items available.</p>
}

Join the conversation! Your thoughts help the community grow.