Click here to Skip to main content
16,004,507 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear all I am having one main view in which I have three tabs for students,Teacher,Parents I am showing their listing in the tabs now I wanted to give the functionality of add new record to all these three tabs for that I created partial view but the issue is my method is not getting call from partial view as I am using jquery ajax call to not load the entire page below is my code for main view and partial view:

MAIN VIEW CODE:
Razor
@model viewModelsWithPartialView.ViewModels.MyViewModel
@section Scripts {

    <script>
        $(document).ready(function () {
            console.log("jquery Loaded from main");
            alert('this is alert from main');
            $('#propertiesDataTable').DataTable();

        });
    </script>
    <script>
        $(document).ready(function () {


            $('#relegion').DataTable();
            $('#customers').DataTable();

        });
    </script>
    @* <script>
        $(document).ready(function () {
            $('#propertiesDataTable').DataTable({
                "processing": true,
                "serverSide": true,
                "filter": true,
                "ajax": {
                    "url": "@Url.Action("LoadProperties", "User")",
                    "type": "POST",
                    "datatype": "json"
                },
                "columns": [
                ],
                "order": [[0, "asc"]],
                "lengthMenu": [[10, 25, 50], [10, 25, 50]]
            });
        });
    </script> *@
    <script>
        $(document).ready(function () {
            $('#myTab a').on('click', function (e) {
                e.preventDefault();
                $(this).tab('show');
            });
        });
    </script>
}

<div class="container">
    <ul class="nav nav-tabs" id="myTab" role="tablist">
        <li class="nav-item" role="presentation">
            <a class="nav-link active" id="property-tab" data-toggle="tab" href="#property" role="tab" aria-controls="property" aria-selected="true">Properties</a>
        </li>
        <li class="nav-item" role="presentation">
            <a class="nav-link" id="reletive-tab" data-toggle="tab" href="#rel" role="tab" aria-controls="mycontroller" aria-selected="false">REl List</a>
        </li>
        <li class="nav-item" role="presentation">
            <a class="nav-link" id="customer-tab" data-toggle="tab" href="#customer" role="tab" aria-controls="customer" aria-selected="false">Customers</a>
        </li>
    </ul>
    <div class="tab-content" id="myTabContent">
        <!-- Property Tab -->
        <div class="tab-pane fade show active" id="property" role="tabpanel" aria-labelledby="property-tab">
            
            <div id="createPropertySection">
                @await Html.PartialAsync("_CreatePropertyPartial")
            </div>

            <h3>Property List</h3>

            <table  id="propertiesDataTable" class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Price</th>
                        <th>Type</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var property in Model.PropertiesList)
                    {
                        <tr>
                            <td>@property.Id</td>
                            <td>@property.Name</td>
                            <td>@property.Price</td>
                            <td>@property.TypeNavigation?.TypeName</td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>

        <div class="tab-pane fade" id="rel" role="tabpanel" aria-labelledby="rel-tab">
            <h3> List</h3>
            <table class="table" id="relegion">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Gender</th>
                        <th> Type</th>
                        <th>Religion</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var rel in Model.relist)
                    {
                        <tr>
                            <td>@rel.Id</td>
                            <td>@rel.Name</td>
                            <td>@rel.Gender</td>
                            <td>@rel.DocumentType</td>
                            <td>@rel.Religion</td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>

        <!-- Customer Tab -->
        <div class="tab-pane fade" id="customer" role="tabpanel" aria-labelledby="customer-tab">
            <h3>Customer List</h3>
            <table class="table" id="customers">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Contact Name</th>
                        <th>Contact Title</th>
                        <th>Address</th>
                        <th>City</th>
                        <th>Region</th>
                        <th>Postal Code</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var customer in Model.CustomersList)
                    {
                        <tr>
                            <td>@customer.CustomerId</td>
                            <td>@customer.ContactName</td>
                            <td>@customer.ContactTitle</td>
                            <td>@customer.Address</td>
                            <td>@customer.City</td>
                            <td>@customer.Region</td>
                            <td>@customer.PostalCode</td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </div>
</div>

Partial View Code:
Razor
@model viewModelsWithPartialView.ViewModels.MyViewModel

<form id="createPropertyForm">
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name" name="Name" required />
    </div>
    <div class="form-group">
        <label for="price">Price</label>
        <input type="number" class="form-control" id="price" name="Price" required />
    </div>
    <div class="form-group">
        <label for="type">Type</label>
        <input type="text" class="form-control" id="type" name="Type" required />
    </div>
    <button type="submit" class="btn btn-primary">Create Property</button>
</form>

@section Scripts {
    
    <script>
        $(document).ready(function () {
            alert('this is me from partial');
            // Handle form submission via AJAX using delegation for dynamically loaded content
            $(document).on('submit', '#createPropertyForm', function (e) {
                e.preventDefault(); // Prevent default form submission

                $.ajax({
                    url: '@Url.Action("CreateProperty", "User")',
                    type: 'POST',
                    data: $(this).serialize(),
                    success: function (response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Property Added',
                                text: 'New property has been added successfully!',
                                showConfirmButton: false,
                                timer: 1500
                            });

                            // Optionally, reload the property list
                            $('#propertyList').load('@Url.Action("PropertyList", "User")');

                            // Clear the form
                            $('#createPropertyForm')[0].reset();
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: response.message,
                            });
                        }
                    },
                    error: function () {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'An error occurred while adding the property.',
                        });
                    }
                });
            });
        });
    </script>
}

Upon checkign I saw the jquery alert is working with main view but not with partial view i have everything in my layout and that is why the main view alert is working datatable are working etc.

What I have tried:

(Duplicated post from above removed)
Posted
Updated 18-Aug-24 19:26pm
v2

1 solution

The problem is that a section can only have one "implementation"; by defining @section Scripts { ... } in your view, the @section Scripts { ... } in your partial views will be ignored.

The standard solution to this problem is to move all of your scripts into a single @section Scripts { ... } in your view. Don't add any scripts into your partial views.

Obviously, that can be quite annoying, and makes it east to forget to include a required script. I tend to use a modified version of this project[^], which provides a custom "asset manager" class to let you register a required script from any view or partial view, and then renders the full set of scripts at the end of the layout.

Unfortunately, that library hasn't been updated since 2013, and doesn't support .NET Core / .NET; but it's fairly simple to update it to add that support.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900