0

I am trying to do CRUD operations on a Master Detail model Department and Employee using modal popup. This is the code I used:

DepartmentController:

[HttpGet]
public IActionResult Create()
{
    Department department= new Department();
    department.Employees.Add(new Employee() { EmployeeId = 1 });
    department.Employees.Add(new Employee() { EmployeeId = 2 });
    department.Employees.Add(new Article() { EmployeeId = 3 });
    return PartialView("_AddDepartmentPartialView",department);
}

[HttpPost]
public IActionResult Create(Department department)
{
    if (department != null)
    {
        _dbcontext.Department.Add(department);
        _dbcontext.SaveChanges();
        return RedirectToAction("Index");
    }
    return View();
}

Index.cshtml:

@model IEnumerable<Department>

@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Theme.cshtml";
}

<div>
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Department</h3>
                    <div class="card-tools">
                        <button type="button" class="btn btn-info" data-toggle="modal" data-target="#addDepartment">
                            <i class="fa fa-plus"></i>
                            Ajouter
                        </button>


                    </div>
                </div>
                <div class="card-body">
                    .....

                </div>
            </div>
        </div>
    </div>
</div>
@await Html.PartialAsync("_AddDepartmentPartialView", new Department())

_AddDepartmentPartialView.cshtml:

@model Department

@{
    ViewData["Title"] = "_AddDepartmentPartialView";
}

<div class="modal fade " role="dialog" tabindex="-1" id="addDepartment" aria-labelledby="addDepartmentLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable" role="document">
        <div class="modal-content">
            <div class="modal-header">
                .....
            </div>
            <div class="modal-body" >
                        .......
                
                        <form asp-action="Create" method="post">
                            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                            
                            
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th>Employee name</th>
                                            <th>Profession</th>
                                            <th>Email</th>
                                        </tr>
                                    </thead>
                                    <tbody>

                                        @for (int i = 0; i < Model.Employees.Count; i++)
                                        {
                                            <tr>
                                                <td>
                                                    @Html.EditorFor(x => x.Employees[i].EmployeeName, new { htmlAttributes = new { @class = "form-control" } })
                                                </td>
                                                <td>
                                                    @Html.EditorFor(x => x.Employees[i].Profession, new { htmlAttributes = new { @class = "form-control" } })
                                                </td>
                                                <td>
                                                    @Html.EditorFor(x => x.Employees[i].Email, new { htmlAttributes = new { @class = "form-control" } })
                                                </td>
                                            </tr>
                                        }

                                    </tbody>
                                </table>
                            
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
                                <button type="submit" class="btn btn-primary" >Sauvegarder</button>
                            </div>
                        </form>
                    
            </div>
            
        </div>

    </div>
</div>

But this PartialView displays only the inputs of the Department model and it doesn't displays the rows of the table to insert employees records (it displays only the head of the table).

So, how to pass both Department and Employee to the partial view?

UPDATE

I tried the solution of @Xinran Shen, the modal popup finally appears with both models Department and Employee. But on Ajouter click, the Index view behind the modal popup changed (a table of all departments is supposed to appear but the nothing is displayed), also i have a Dropdownlist in the modal popup it appears empty and it doesn't populated. I think because i am using a custom Layout page but i couldn't find where is the problem exactly. Any help??

user4374239
  • 93
  • 2
  • 11

1 Answers1

1

In Index.cshtml, You use:

@await Html.PartialAsync("_AddDepartmentPartialView", new Department())

to load the partial View, It will not create partial view by Create get method. And you just pass new Department() into partial View, The Department passed into view is null, So it doesn't display the rows of table.

You can set an onclick event on Ajouter button, When user click the button, It will access Create get method and Initialize Department with the initial value, Then return partial view to the index view.

.............
<button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#addDepartment" onclick="GetDetails()">
    <i class="fa fa-plus"></i>
    Ajouter
</button>
..........

<div class="card-body" id="Body">

</div>

...............

<script>
    function GetDetails() {
        $.ajax({
            type: "Get",
            url: "/Home/Create",
            success: function (res) {
                
                $("#Body").html(res);
                $("#addDepartment").modal('show');
            }
        });
    }
</script>

Then when you click button, It will show the full table.

enter image description here

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12
  • Still not showing the table – user4374239 Oct 14 '22 at 08:56
  • When you click button, Partial view will not display? You just want to show the Department Initialized in Create method in table right? – Xinran Shen Oct 14 '22 at 09:04
  • Yes on click button the modal popup displays only the Department inputs (master) and it doesn't display the table to fill the Employee table (detail) – user4374239 Oct 14 '22 at 09:07
  • Have you deleted `@await Html.PartialAsync("_AddDepartmentPartialView", new Department())` in index view? – Xinran Shen Oct 14 '22 at 09:11
  • No, when i deleted it the modal popup didn't show at all. – user4374239 Oct 14 '22 at 09:17
  • You need to delete it. Check my answer, when Click button, It will send ajax to Create get method, Then this method will return `_AddDepartmentPartialView`, I use `$("#Body").html(res);` to add this partial view into my view and use `$("#addDepartment").modal('show')` to display it. – Xinran Shen Oct 14 '22 at 09:20
  • I deleted it and now the modal popup doesn't show at all – user4374239 Oct 14 '22 at 09:37
  • When you click button, Does the project can run into Create method? When this method return , You can debug if res in `success: function (res) ` has the value, Does any error in console in browser? I create a demo to test it and it success , You need to check if there is any thing wrong in your project. – Xinran Shen Oct 14 '22 at 09:40
  • Sorry, From your description, It's hard to determine what going wrong, I don't know how you pass data from Create to partial view, You can try to use `ViewBag`. I suggest you to create a new issue about your new question, Because many questions in one issue will make this issue less readable. If this answer help you show modal successfully, Can your mark it as an answer? Thank you so much. – Xinran Shen Oct 18 '22 at 01:19