0

The title is the error I keep getting, I have been following a tutorial for a uni project of mine. However, I hit a stage where I need to make CRUD operations. This is the error I am given: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.Data.DataRow]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable. And here is the rest of it:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[System.Data.DataRow]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[Quilted_Bear_Inventory_Management_System.Models.Products]'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[System.Data.DataRow]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[Quilted_Bear_Inventory_Management_System.Models.Products]'.] System.Web.Mvc.ViewDataDictionary1.SetModel(Object value) +175 System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +107 System.Web.Mvc.WebViewPage1.SetViewData(ViewDataDictionary viewData) +49 System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +99 System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList1 filters, ActionResult actionResult) +52 System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +198 System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +100 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45 System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9836613 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163

This is my code from my ProductsController:

namespace Quilted_Bear_Inventory_Management_System.Controllers
{
    public class ProductsController : Controller
    {
        // GET: Products
        readonly string myConnectionString = "server = ; user = ; password = ; database = ";

        public ActionResult Index()
        {
            MySqlConnection myConnection = new MySqlConnection(myConnectionString);
            MySqlDataAdapter dataAdapter = new MySqlDataAdapter("SelectAllProducts", myConnection); //I think the problem is here, how am I fixing it though? --Fixed but why can't it be put into a class?
            dataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;

            DataTable dataTable = new DataTable();

            dataAdapter.Fill(dataTable);

            return View(dataTable.AsEnumerable().ToList());
        }
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreateProduct(Products product)
        {
            //insert statement
            return RedirectToAction("Index", "Dashboard");

        }
        [HttpPost]
        public bool Delete(int ID)
        {
            try
            {
                //delete statement where id = id
                return true;
            }
            catch (System.Exception)
            {
                return false;
            }
        }
        public ActionResult Update(int ID)
        {
            //update view where id is id
            return View();
        }
        [HttpPost]
        public ActionResult UpdateDoctor(Products product)
        {
            //update statement
            return RedirectToAction("Index", "Doctors");
        }
    }
}

Last but not least my Products Index Page:

@{
    ViewBag.Title = "Dashboard";
    Layout = "~/Views/Shared/_DashboardLayout.cshtml";
}
@model IEnumerable<Quilted_Bear_Inventory_Management_System.Models.Products>
<section class="content-header">
    <h1>
        Products
    </h1>
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active">Products</li>
    </ol>
</section>
<!-- Main content -->
<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="box">
                <div class="box-header">
                    <h3 class="box-title">Manage Products</h3>
                </div>
                <!-- /.box-header -->
                <div class="box-body">
                    <table id="example1" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Product ID</th>
                                <th>SKU</th>
                                <th>Product Name</th>
                                <th>Unit Price</th>
                                <th>Units in Stock</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var item in Model)
                            {
                                <tr>
                                    <td>@Html.DisplayFor(modelItem => item.ProductID)</td>
                                    <td>@Html.DisplayFor(modelItem => item.SKU)</td>
                                    <td>@Html.DisplayFor(modelItem => item.ProductName)</td>
                                    <td>@Html.DisplayFor(modelItem => item.UnitPriceProduct)</td>
                                    <td>@Html.DisplayFor(modelItem => item.UnitsInStock)</td>
                                    <td><a href="Products/Update/@item.ProductID">Update</a> | <a href="" onclick="Delete('@item.ProductID')">Delete</a></td>
                                </tr>
                            }
                    </table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>
        <!-- /.col -->
    </div>
    <!-- /.row -->
</section>

<!-- DataTables -->
<script src="~/bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="~/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
<!-- page script -->
<script>
    $(function () {
        $('#example1').DataTable();
    });
    function Delete(id){
        var txt;
        var r = confirm("Are you sure you want to Delete?");
        if (r == true) {

            $.ajax(
            {
                type: "POST",
                url: '@Url.Action("Delete", "Doctors")',
                data: {
                    id: id
                },
                error: function (result) {
                    alert("error");
                },
                success: function (result) {
                    if (result == true) {
                        var baseUrl="/Doctors";
                        window.location.reload();
                    }
                    else {
                        alert("There is a problem, Try Later!");
                    }
                }
            });
        }
    }
</script>

Any help or guidance would be appreciated, I am lost. Thank you!

BenjaminD
  • 29
  • 1
  • 7
  • The problem is that you build your view to accept a collection of `Models.Products` but you are passing it a collection of datarows. Do you have a method to convert a datarow to an object? Or should you use EF os another framework to create entities from a data source? – D Stanley Mar 03 '20 at 19:49
  • @DStanley Hey, thanks for the reply. I don't really get what you mean. I was hoping that I can send off the data table and the view will loop around everything in that table, is this not possible? – BenjaminD Mar 03 '20 at 19:59
  • It's possible, but you'd need to redesign your view to process datarows. Seems like you've mixed two turorials - one to build the view from objects (whicih is cleaner) and one to get data. Honestly I'd either switch to EF or write a conversion method to create an object from a DataRow. – D Stanley Mar 03 '20 at 20:04
  • @DStanley Ah, I get what you mean now, I do actually have EntityFramework installed through NuGet. So what am I supposed to do with that? – BenjaminD Mar 03 '20 at 20:08
  • construct a list of ``Products`` for all ``Datable.Rows`` and send it to the ``View``, [the first answer](https://stackoverflow.com/questions/1346132/how-do-i-extract-data-from-a-datatable) will help you to get data from ``Rows`` – Mohammed Sajid Mar 03 '20 at 20:32
  • @Sajid Oh, I think I am starting to get it, so data rows work hand-in hand with DataTables. That's handy. I will give that a go and come back with my findings. Cheers chief! – BenjaminD Mar 03 '20 at 20:59

0 Answers0