Create and List Views in a Single Razor View Using Partial Views

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>
}

Example Cascading Dropdown lists in ASP.NET Core
 

ViewModel

public class StateSchoolVm
{
    public string SelectedState { get; set; }
    public string SelectedSchool { get; set; }
    public List<string> States { get; set; }
    public List<string> Schools { get; set; }
    public StateSchoolVm()
    {
        States = new List<string>();
        Schools = new List<string>();
    }
}

Controller

public class DropdownController : Controller
{
    private static readonly Dictionary<string, List<string>> StateSchoolData = new Dictionary<string, List<string>>
    {
        { "MAIN", new List<string> { "A", "D" } },
        { "SIDE", new List<string> { "B", "C" } }
    };
    public IActionResult Index()
    {
        var viewModel = new StateSchoolVm
        {
            States = StateSchoolData.Keys.ToList()
        };
        return View(viewModel);
    }
    [HttpPost]
    public IActionResult GetSchools(string state)
    {
        if (StateSchoolData.ContainsKey(state))
        {
            return Json(StateSchoolData[state]);
        }
        return Json(new List<string>());
    }
}

View (Index. cshtml)

@model myprojectname.ViewModels.StateSchoolVm
<div>
    <label>State:</label>
    <select id="stateDropdown">
        <option value="">Select State</option>
        @foreach (var state in Model.States)
        {
            <option value="@state">@state</option>
        }
    </select>
</div>
<div>
    <label>School:</label>
    <select id="schoolDropdown">
        <option value="">Select School</option>
    </select>
</div>
@section Scripts {
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#stateDropdown').change(function () {
                var selectedState = $(this).val();
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("GetSchools", "Dropdown")',
                    data: { state: selectedState },
                    success: function (data) {
                        var schoolDropdown = $('#schoolDropdown');
                        schoolDropdown.empty();
                        schoolDropdown.append($('<option>').text('Select School').attr('value', ''));
                        $.each(data, function (i, school) {
                            schoolDropdown.append($('<option>').text(school).attr('value', school));
                        });
                    }
                });
            });
        });
    </script>
}

This example demonstrates how to combine create and list views in a single Razor view and how to create cascading dropdown lists using jQuery and AJAX in ASP.NET Core.