Click here to Skip to main content
15,445,641 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Guys,, I'm trying to show partial view in another view. The partial view will show in Create.cshtml as the model name is PinjamanModel(strongly typed). The partial view use Detail_Pinjaman_Buku as the model name, I want is when data save then load the partial view in form Create.cshtml based the ID/Kode_Pinjam. when the code running I get error InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'www.si.perpustakaan.Models.Detail_Pinjaman_Buku', but this ViewDataDictionary instance requires a model item of type 'System.Data.DataTable'.
Any help could be appriciate.

What I have tried:

This is the Create.cshtml
@using www.si.perpustakaan
@model PinjamanModel
@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/AdminDashboard/_Layout.cshtml";
}
<script src="~/lib/jquery/dist/jquery.3.3.1.min.js"></script>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/assets/plugins/jquery-ui/jquery-ui.js"></script>
<link href="~/assets/plugins/jquery-ui/jquery-ui.css" rel="stylesheet" />
 
<script src="~/assets/plugins/sweetalert2/sweetalert2.js"></script>
<link href="~/assets/plugins/sweetalert2/sweetalert2.css" rel="stylesheet" />
 
<div class="tab-content">
    <div class="tab-pane tabs-animation fade show active" id="tab-content-0" role="tabpanel">
        <div class="row">
            <div class="col-md-12">
                <div class="main-card mb-3 card">
                    <div class="card-body">
                        <!-- Modal Header -->
                        <div class="modal-header bg bg-success">
                            <div align="center">
                                <h4 class="modal-title">Add Data Pinjaman</h4>
                            </div>
                        </div>
                        <hr />
                        <form asp-action="" asp-controller="" method="post">
                            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Kode_Pinjam" class="control-label"></label>
                                        <input asp-for="Kode_Pinjam" id="Kode_Pinjam" name="Kode_Pinjam" class="form-control"/>
                                        <span asp-validation-for="Kode_Pinjam" class="text-danger"></span>
                                    </div>
                                </div>
 
                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Tanggal_Pinjam" class="control-label"></label>
                                        <input asp-for="Tanggal_Pinjam" class="form-control" placeholder="Enter Tanggal Pinjam Buku" />
                                        <span asp-validation-for="Tanggal_Pinjam" class="text-danger"></span>
                                    </div>
                                </div>
 
                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Tanggal_Kembali" class="control-label"></label>
                                        <input asp-for="Tanggal_Kembali" class="form-control" placeholder="Enter Tanggal Kembali Buku" />
                                        <span asp-validation-for="Tanggal_Kembali" class="text-danger"></span>
                                    </div>
                                </div>
 
                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Kode_Anggota" class="control-label"></label>
                                        <div class="input-group">
                                            <input asp-for="Kode_Anggota" class="form-control" id="Kode_Anggota" placeholder="Enter Kode Anggota" required />
                                            <div class="input-group-append">
                                                <button type="button" id="CekNamaAnggota" class="btn btn-warning">Cari Kode Anggota</button>
                                            </div>
                                        </div>
                                        <span asp-validation-for="Kode_Anggota" class="text-danger"></span>
                                    </div>
                                </div>
 
                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Nama_Anggota" class="control-label"></label>
                                        <input asp-for="Nama_Anggota" class="form-control" id="Nama_Anggota" placeholder="Enter Nama Anggota" readonly="readonly" />
                                    </div>
                                    <span asp-validation-for="Nama_Anggota" class="text-danger"></span>
                                </div>
 
                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Kode_Petugas" class="control-label"></label>
                                        <div class="input-group">
                                            <input asp-for="Kode_Petugas" class="form-control" id="Kode_Petugas" placeholder="Enter Kode Petugas" required />
                                            <div class="input-group-append">
                                                <button type="button" id="CekNamaPetugas" class="btn btn-warning">Cari Kode Petugas</button>
                                            </div>
                                        </div>
                                        <span asp-validation-for="Kode_Petugas" class="text-danger"></span>
                                    </div>
                                </div>
 
                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Nama_Petugas" class="control-label"></label>
                                        <input asp-for="Nama_Petugas" class="form-control" id="Nama_Petugas" placeholder="Enter Nama Petugas" readonly="readonly" />
                                    </div>
                                    <span asp-validation-for="Nama_Petugas" class="text-danger"></span>
                                </div>
 
                                @*Data Buku*@
                                <div class="col-md-12">
                                    <div class="main-card mb-3 card">
                                        <div class="card-body">
                                            <!-- Modal Header -->
                                            <div class="modal-header bg bg-primary">
                                                <div align="center">
                                                    <h4 class="modal-title">Data Buku</h4>
                                                </div>
                                            </div>
                                            <hr />
 
                                            <table>
                                                <thead>
                                                    <tr>
                                                        <th>Kode Buku</th>
                                                        <th>Judul</th>
                                                        <th>Penulis</th>
                                                        <th>Penerbit</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td><input asp-for="Kode_Buku" class="form-control" id="Kode_Buku" placeholder="Enter Kode Buku" name="Kode_Buku" required /></td>
                                                        <td><input asp-for="Judul" class="form-control" id="Judul" placeholder="Enter Judul Buku" name="Judul" readonly="readonly" /></td>
                                                        <td><input asp-for="Penulis" class="form-control" id="Penulis" placeholder="Enter Penulis" name="Penulis" readonly="readonly" /></td>
                                                        <td><input asp-for="Penerbit" class="form-control" id="Penerbit" placeholder="Enter Penerbit" name="Penerbit" readonly="readonly" /></td>
                                                        <td><button type="button" id="Btn_Search_Kode_Buku" class="btn btn-warning btn-sm">class="fa fa-search"></td>
                                                        <td><button type="button" id="Btn_Add_Search_Kode_Buku" class="btn btn-success btn-sm">^__i class="fa fa-plus"> Add</button></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                            <hr />
                                            
                                            <div id="ViewHolder">
                                                <partial name="~/Views/Shared/_DetailPinjamanBuku.cshtml" model="new Detail_Pinjaman_Buku()"/>
                                            </div>
                                            
                                            @*Detail Pinjaman Buku*@
                                            @*<table class="table table-responsive table-hover">
                                                <thead class="bg bg-dark text-center align-middle text-white table-bordered">
                                                    <tr>
                                                        <th width="15%">Kode Buku</th>
                                                        <th width="35%">Judul</th>
                                                        <th width="25%">Penulis</th>
                                                        <th width="25%">Penerbit</th>
                                                    </tr>
                                                </thead>
                                                <tbody class="tbody">
 
                                                </tbody>
                                            </table>*@
 
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <div align="center">
                                            <input type="submit" value="Save Data Pinjaman" class="btn btn-success" />
                                        </div>
                                    </div>
                                    <div>
                                        <a asp-action="Index">^__i class="fa fa-arrow-alt-circle-left"> Back to List</a>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
 
<script type="text/javascript">
    $(document).ready(function () {
        $('#Btn_Add_Search_Kode_Buku').on("click", function () {
            var ObjectBuku = {
                Kode_Pinjam: $("#Kode_Pinjam").val(),
                Kode_Buku: $("#Kode_Buku").val(),
                Judul: $("#Judul").val(),
                Penulis: $("#Penulis").val(),
                Penerbit: $("#Penerbit").val()
            };
            $.ajax({
                url: "/Pinjaman/SaveData_Search_Buku",
                data: JSON.stringify(ObjectBuku),
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    window.alert("Data successfully saved..");
                    
                     //After data succesfully inserted to database based Kode_Pinjam
                     //And then show back data to partial view looping into table 
                    $('ViewHolder').load("/Pinjaman/GetDetailPinjamanBuku",
                        { Kode_Pinjam: $('#Kode_Pinjam').val(), viewName: "_DetailPinjamanBuku"});
                },
                error: function (errormessage) {
                    window.alert(errormessage.responseText);
                }
            });
            return false;
        });
    });
</script>
 
<script type="text/javascript" lang="javascript">
    $("[id*=Tanggal_Pinjam]").attr("ReadOnly", true)
    $("[id*=Tanggal_Pinjam]").datepicker(
        {
            dateFormat: "yy/mm/dd"
        });
 
    $("[id*=Tanggal_Kembali]").attr("ReadOnly", true)
    $("[id*=Tanggal_Kembali]").datepicker(
        {
            dateFormat: "yy/mm/dd"
        });
</script>
 
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}


_DetailPinjamanBuku.cshtml(This the partial view)
@model System.Data.DataTable
@if (Model != null)
{
    <table style="width: 100%;" id="myTable" class="table table-hover table-responsive table-borderless">
        <thead class="bg bg-dark text-center align-middle text-white">
            <tr>
                <th>Kode Buku</th>
                <th>Judul</th>
                <th>Penulis</th>
                <th>Penerbit</th>
            </tr>
        </thead>
        <tbody>
            @for (int i = 0; i < Model.Rows.Count; i++)
            {
                <tr class="text-center">
                    <td style="width:15%">@Model.Rows[i]["Kode_Buku"]</td>
                    <td style="width:35%">@Model.Rows[i]["Judul"]</td>
                    <td style="width:25%">@Model.Rows[i]["Penulis"]</td>
                    <td style="width:25%">@Model.Rows[i]["Penerbit"]</td>
                </tr>
            }
        </tbody>
    </table>
}

The Controller.cs
[HttpPost]
        public IActionResult GetDetailPinjamanBuku(string Kode_Pinjam, string viewName)
        {
            Detail_Pinjaman_Buku _Detail_Pinjaman_Buku = new Detail_Pinjaman_Buku();
            DataTable dataTableDetail_Pinjaman_Buku = new DataTable();
            if (viewName == "_DetailPinjamanBuku")
                using (SqlConnection con = new SqlConnection(this._configuration.GetConnectionString("db_perpustakaan")))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        con.Open();
                        cmd.Connection = con;
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = "Select * From View_Detail_Pinjaman_Buku Where Kode_Pinjam= '" + Kode_Pinjam.Trim() + "'";
                        cmd.Parameters.AddWithValue("@Kode_Pinjam", Kode_Pinjam);
                        using (SqlDataAdapter _SqlDataAdapter = new SqlDataAdapter(cmd))
                        {
                            _SqlDataAdapter.Fill(dataTableDetail_Pinjaman_Buku);
                        }
                        if (dataTableDetail_Pinjaman_Buku.Rows.Count == 1)
                        {
                            _Detail_Pinjaman_Buku.Kode_Buku = dataTableDetail_Pinjaman_Buku.Rows[0]["Kode_Buku"].ToString();
                            _Detail_Pinjaman_Buku.Judul = dataTableDetail_Pinjaman_Buku.Rows[0]["Judul"].ToString();
                            _Detail_Pinjaman_Buku.Penulis = dataTableDetail_Pinjaman_Buku.Rows[0]["Penulis"].ToString();
                            _Detail_Pinjaman_Buku.Penerbit = dataTableDetail_Pinjaman_Buku.Rows[0]["Penerbit"].ToString();
                        }
                    }
                }
            return PartialView(viewName, _Detail_Pinjaman_Buku);
        }
Posted
Updated 15-Aug-21 23:37pm

1 solution

Quote:
The partial view use Detail_Pinjaman_Buku as the model name ...
Razor
<partial name="~/Views/Shared/_DetailPinjamanBuku.cshtml" model="new Detail_Pinjaman_Buku()"/>
Razor
@model System.Data.DataTable
The model item ... is of type 'Detail_Pinjaman_Buku', but this ViewDataDictionary instance requires a model item of type 'System.Data.DataTable'.
Read your code again. The model type declared for your partial view is System.Data.DataTable, NOT Detail_Pinjaman_Buku.

Either correct the model type in your partial view, or correct the model you pass in to the partial view.

Edit:
C#
cmd.CommandText = "Select * From View_Detail_Pinjaman_Buku Where Kode_Pinjam= '" + Kode_Pinjam.Trim() + "'";
Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
 
Share this answer
 
v2
Comments
tri setia 16-Aug-21 23:50pm     CRLF
Thanks sir,, Problem Solved,, I'm just change this line <partial name="~/Views/Shared/_DetailPinjamanBuku.cshtml" model="new System.Data.DataTable">

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