MVC asp.net PartialView 导致无参数构造函数错误?

发布于 2024-12-05 12:57:57 字数 20473 浏览 2 评论 0原文

MVC 2.0 应用程序部分视图存在问题,访问时突然出现问题,并且内容实际上位于 ViewData 中,这是可怕的无参数构造函数错误。我已经尽我所能地遵循了代码,但我没有得到任何结果。这是我的代码:

Controller:

  using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.ComponentModel;
    using CINet.Areas.CatalystSearch.Models.Interfaces;
    using CINet.Areas.CatalystSearch.Models.Repository;
    using CINet.Areas.CatalystSearch.Models.Entities;

    namespace CINet.Areas.CatalystSearch.Controllers
    {
        public class CatalystSearchController : Controller
        {
           // private SqlCatalystRepository _catalystItemRepository;
            private ICatalystRepository _catalystInterface;
            public int PageSize = 10; // Regulates size of page

        #region CONSTRUCTOR

        /// <summary>
        /// Constructor which sets the passed repository to the local current 
        /// repository
        /// </summary>
        /// <param name="catalystRepository">Interface repository for controller</param>
        public CatalystSearchController()
        {

        }

        #endregion

        #region  DEFAULT VIEW


        public ViewResult List([DefaultValue("")] string manufactureName, [DefaultValue("")] string manufacturePartNumber, [DefaultValue("")] string description, [DefaultValue(1)] int page)
        {

            IQueryable<CatalystItem> query = null;
            CatalystFilter userFilter = new CatalystFilter();
            int totalItems = 0;

           // Be sure that the manufacture drop down has been selected
            if (manufactureName != "")
            {
                // Set up CatalystFilter
                userFilter.Manufacture = manufactureName;
               userFilter.DescriptionFilter = description;
                userFilter.ManufacturePartNumberFilter = manufacturePartNumber;

                // connection string for SQL
                string connString = "Data Source=se-cinet-dev;Initial Catalog=cinet;User ID=sa;Password=Carouse1";


                // Get interface
                _catalystInterface = new CatalystRepository(connString);


                // Collects data from SQL repository and updates private local copy
               // _catalystItemRepository = new SqlCatalystRepository(connString);

                // Fills with list of Catalystitems based on filter.
                query = _catalystInterface.GetCatalystItems(userFilter, page, PageSize);
                // query = _catalystItemRepository.GetItems(userFilter, page, PageSize);

                // Returns int of total items in list
                totalItems = _catalystInterface.GetTotalOfItems(userFilter);
                // totalItems = _catalystItemRepository.GetTotalOfItems(userFilter);

                // Set up view model for passing to View
                var viewModel = new CatalystModel
                {

                    catalystItems = query.ToList(),
                    catalystFilter = userFilter,

                    /* Pass Paging properties to model*/
                    PagingInfo = new PagingInfo
                    {
                        CurrentPage = page,
                        ItemsPerPage = PageSize,
                        TotalItems = totalItems

                    },
                    ManufactureName = manufactureName

                };

                // View Data to be passed to SearchView
                ViewData["catalystItems"] = viewModel;


                return View(viewModel);
            }

            else
            {
                var viewModel = new CatalystModel();
                return View(viewModel);
            }
        }

        #endregion

        #region SEARCH VIEW

        /// <summary>
        /// Partial View used to display results from controller
        /// </summary>
        /// <param name="model"> model passed via ViewData from List View</param>
        /// <returns></returns>
        [ChildActionOnly]
        public ViewResult SearchView(CatalystModel model)
        {
            return View(model);
        }

        #endregion

    }
}

listView:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CINet.Areas.CatalystSearch.Models.Entities.CatalystModel>" %>
<%@ Import Namespace="CINet.Areas.CatalystSearch.HtmlHelpers" %>
<%@ Import Namespace="CINet.Areas.CatalystSearch.Models" %>
<%@ Import Namespace="CINet.Areas.CatalystSearch.Models.Interfaces" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <div>
        <center>
            <strong>
                <%= Html.ValidationSummary("Please fill out required Fields") %></strong> 

                <h1>Catalyst Search Provider</h1>
            <hr />
            <%-- "Search","Catalyst" --%>
            <% 
                using (Html.BeginForm())
                { %>
            <table border="1">

               <tr>
                <td>Enter Description (optional):</td>
                <td>
                <%: Html.TextBoxFor(x=>x.Description) %>
                </td>
                </tr>

                <tr>
                <td>Enter Part Number (optional):</td>
                <td>
                <%: Html.TextBoxFor(x=>x.ManufacturePartNumber) %>
                </td>
                </tr>

                <tr>
                    <td>Choose Manufacture:
                    </td>
                    <td>
                        <%: Html.DropDownListFor(x => x.ManufactureName, Model.GetAllManufactures()) %>
                       <%--  <%: Html.DropDownList("ManufactureName", Model.GetAllManufactures(),"Choose Item")%> --%>
                    </td>
                </tr>
                <tr>
                    <td>
                        &nbsp
                    </td>
                    <td>
                        <input type="submit" name="Search" value="Search" />
                    </td>
                </tr>
            </table>
            <% } Html.EndForm();  %>
            <!-- RENDERS PARTIAL VIEW TO DISPLAY GRID WITH SEARCH RESULTS -->
            <% Html.RenderAction("SearchView", ViewData["catalystItems"]); %>
            <br />
        </center>
    </div>
    <div class="pager">

       <% if (Model.PagingInfo != null)
          { %>
        <%: Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new { page = x, manufactureName = Model.catalystFilter.Manufacture, description = Model.catalystFilter.DescriptionFilter, manufacturePartNumber = Model.catalystFilter.ManufacturePartNumberFilter }))%>
        <% } %>
    </div>

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
</asp:Content>


SearchView:

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CINet.Areas.CatalystSearch.Models.Entities.CatalystModel>" %>
<%@ Import Namespace="CINet.Areas.CatalystSearch.HtmlHelpers" %>
<%@ Import Namespace="CINet.Areas.CatalystSearch.Models" %>

 <div>
    <% if (Model.catalystItems != null)
       { %>
        <table class="CatalystTableSpacer">
            <tr>
                <td>
                    Contract Price
                </td>
                <td>
                    Description
                </td>
                <td>
                    Manufacture Name
                </td>
                <td>
                    Manufacture Part Number
                </td>
                <td>
                    MSRP Price
                </td>
                <td>
                    Quantity Available
                </td>

            </tr>
            <% foreach (var items in Model.catalystItems)
               {%>
            <tr>
                <td>
                    <%: items.ContractPrice%>
                </td>
                <td>
                    <%: items.Description%>
                </td>
                <td>
                    <%: items.ManufactureName%>
                </td>
                <td>
                    <%: items.ManufacturePartNumber%>
                </td>
                <td>
                   <%: items.MSRPrice%>
                </td>
                <td>
                    <%: items.QuantityAvailable%>
                </td>

            </tr>
            <% }
       }

                %>
            </table>

           </div>

CatalystModel

   using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CINet.Areas.CatalystSearch.Models.Entities;
using System.ComponentModel.DataAnnotations;
using CINet.Areas.CatalystSearch.Models.Repository;
using CINet.Areas.CatalystSearch.Models.Interfaces;

namespace CINet.Areas.CatalystSearch.Models.Entities
{
    public class CatalystModel
    {

          #region PRIVATE FIELDS

        private string _connectionString = "Data Source=se-cinet-dev;Initial Catalog=cinet;User ID=sa;Password=Carouse1"; // connection string for SQL
        private ICatalystRepository _repository = null;

        #endregion
    #region PUBLIC PROPERTIES

    public IList<CatalystItem> catalystItems { get; set; }
    public PagingInfo PagingInfo { get; set; }
    public CatalystFilter catalystFilter { get; set; }
    public SelectList Manufactures { get; set; }
    public SelectList Categories { get; set; }

    [Required]
    public string ManufactureName { get; set; }

    public string Description { get; set; }

    public string ManufacturePartNumber { get; set; }

    #endregion


    #region CONSTRUCTOR

    /// <summary>
    /// Constructor instantiates SQL DB Connection
    /// </summary>
    public CatalystModel()
    {
        _repository = new CatalystRepository(_connectionString);
     //   Manufactures = GetAllManufactures();
    }



    #endregion

    #region PUBLIC GET LISTS

    /// <summary>
    /// Returns ALL Manufactures in Database
    /// </summary>
    /// <returns></returns>
    public SelectList GetAllManufactures()
    {
        SelectList manufactureNameSelectList;
        List<Manufacture> manufactureTempList = new List<Manufacture>();

        // Get List from DB
        manufactureTempList = _repository.GetManufactureList();

        // PUSH LIST INTO SELECT LIST
        manufactureNameSelectList = new SelectList(manufactureTempList, "ManufactureName", "ManufactureName");

        return manufactureNameSelectList;
    }



    #endregion

}

}

错误发生在调用 SearchView 的 ListView 中:

<% Html.RenderAction("SearchView", ViewData["catalystItems"]); %>

有什么帮助吗?

实际错误:

Server Error in '/' Application.
--------------------------------------------------------------------------------

No parameterless constructor defined for this object. 
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.MissingMethodException: No parameterless constructor defined for this object.

Source Error: 


Line 53:             <!-- RENDERS PARTIAL VIEW TO DISPLAY GRID WITH SEARCH RESULTS -->
Line 54:           <%-- <% Html.RenderPartial("SearchView", ViewData["catalystItems"]); %>
Line 55:           --%> <% Html.RenderAction("SearchView", ViewData["catalystItems"]); %>
Line 56:             
Line 57:             <br />


Source File: c:\Users\gcoleman\Documents\Source Code\Sandbox\Jonathan Henk\MVC\CINet\CINet\Areas\CatalystSearch\Views\CatalystSearch\List.aspx    Line: 55 

Stack Trace: 


[MissingMethodException: No parameterless constructor defined for this object.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
   System.Activator.CreateInstance(Type type) +6
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +403
   System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +544
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +479
   System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +45
   System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +658
   System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +147
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +98
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2504
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +548
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +475
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +181
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830
   System.Web.Mvc.Controller.ExecuteCore() +136
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.Mvc.<>c__DisplayClassa.<EndProcessRequest>b__9() +44
   System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +34
   System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +76
   System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Action action) +113
   System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.EndProcessRequest(IAsyncResult result) +124
   System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1072

[HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.]
   System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +3058371
   System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +77
   System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +28
   System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +22
   System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +766
   System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +98
   System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, Object routeValues) +65
   ASP.areas_catalystsearch_views_catalystsearch_list_aspx.__RenderContent1(HtmlTextWriter __w, Control parameterContainer) in c:\Users\gcoleman\Documents\Source Code\Sandbox\Jonathan Henk\MVC\CINet\CINet\Areas\CatalystSearch\Views\CatalystSearch\List.aspx:55
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +109
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
   System.Web.UI.Control.Render(HtmlTextWriter writer) +10
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   ASP.views_shared_site_master.__Renderform1(HtmlTextWriter __w, Control parameterContainer) in c:\Users\gcoleman\Documents\Source Code\Sandbox\Jonathan Henk\MVC\CINet\CINet\Views\Shared\Site.Master:26
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +109
   System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +8820669
   System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +31
   System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +53
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +40
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
   System.Web.UI.Control.Render(HtmlTextWriter writer) +10
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
   System.Web.UI.Page.Render(HtmlTextWriter writer) +29
   System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer) +56
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3060




--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.237 

Having an issue with an MVC 2.0 application partial view that all of the sudden when accessed and stuff is actually in the ViewData, the dreaded No parameterless Constructor error. I Have followed the code as much as I can and I'm getting no where. Here is my code:

Controller:

  using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.ComponentModel;
    using CINet.Areas.CatalystSearch.Models.Interfaces;
    using CINet.Areas.CatalystSearch.Models.Repository;
    using CINet.Areas.CatalystSearch.Models.Entities;

    namespace CINet.Areas.CatalystSearch.Controllers
    {
        public class CatalystSearchController : Controller
        {
           // private SqlCatalystRepository _catalystItemRepository;
            private ICatalystRepository _catalystInterface;
            public int PageSize = 10; // Regulates size of page

        #region CONSTRUCTOR

        /// <summary>
        /// Constructor which sets the passed repository to the local current 
        /// repository
        /// </summary>
        /// <param name="catalystRepository">Interface repository for controller</param>
        public CatalystSearchController()
        {

        }

        #endregion

        #region  DEFAULT VIEW


        public ViewResult List([DefaultValue("")] string manufactureName, [DefaultValue("")] string manufacturePartNumber, [DefaultValue("")] string description, [DefaultValue(1)] int page)
        {

            IQueryable<CatalystItem> query = null;
            CatalystFilter userFilter = new CatalystFilter();
            int totalItems = 0;

           // Be sure that the manufacture drop down has been selected
            if (manufactureName != "")
            {
                // Set up CatalystFilter
                userFilter.Manufacture = manufactureName;
               userFilter.DescriptionFilter = description;
                userFilter.ManufacturePartNumberFilter = manufacturePartNumber;

                // connection string for SQL
                string connString = "Data Source=se-cinet-dev;Initial Catalog=cinet;User ID=sa;Password=Carouse1";


                // Get interface
                _catalystInterface = new CatalystRepository(connString);


                // Collects data from SQL repository and updates private local copy
               // _catalystItemRepository = new SqlCatalystRepository(connString);

                // Fills with list of Catalystitems based on filter.
                query = _catalystInterface.GetCatalystItems(userFilter, page, PageSize);
                // query = _catalystItemRepository.GetItems(userFilter, page, PageSize);

                // Returns int of total items in list
                totalItems = _catalystInterface.GetTotalOfItems(userFilter);
                // totalItems = _catalystItemRepository.GetTotalOfItems(userFilter);

                // Set up view model for passing to View
                var viewModel = new CatalystModel
                {

                    catalystItems = query.ToList(),
                    catalystFilter = userFilter,

                    /* Pass Paging properties to model*/
                    PagingInfo = new PagingInfo
                    {
                        CurrentPage = page,
                        ItemsPerPage = PageSize,
                        TotalItems = totalItems

                    },
                    ManufactureName = manufactureName

                };

                // View Data to be passed to SearchView
                ViewData["catalystItems"] = viewModel;


                return View(viewModel);
            }

            else
            {
                var viewModel = new CatalystModel();
                return View(viewModel);
            }
        }

        #endregion

        #region SEARCH VIEW

        /// <summary>
        /// Partial View used to display results from controller
        /// </summary>
        /// <param name="model"> model passed via ViewData from List View</param>
        /// <returns></returns>
        [ChildActionOnly]
        public ViewResult SearchView(CatalystModel model)
        {
            return View(model);
        }

        #endregion

    }
}

listView:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CINet.Areas.CatalystSearch.Models.Entities.CatalystModel>" %>
<%@ Import Namespace="CINet.Areas.CatalystSearch.HtmlHelpers" %>
<%@ Import Namespace="CINet.Areas.CatalystSearch.Models" %>
<%@ Import Namespace="CINet.Areas.CatalystSearch.Models.Interfaces" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <div>
        <center>
            <strong>
                <%= Html.ValidationSummary("Please fill out required Fields") %></strong> 

                <h1>Catalyst Search Provider</h1>
            <hr />
            <%-- "Search","Catalyst" --%>
            <% 
                using (Html.BeginForm())
                { %>
            <table border="1">

               <tr>
                <td>Enter Description (optional):</td>
                <td>
                <%: Html.TextBoxFor(x=>x.Description) %>
                </td>
                </tr>

                <tr>
                <td>Enter Part Number (optional):</td>
                <td>
                <%: Html.TextBoxFor(x=>x.ManufacturePartNumber) %>
                </td>
                </tr>

                <tr>
                    <td>Choose Manufacture:
                    </td>
                    <td>
                        <%: Html.DropDownListFor(x => x.ManufactureName, Model.GetAllManufactures()) %>
                       <%--  <%: Html.DropDownList("ManufactureName", Model.GetAllManufactures(),"Choose Item")%> --%>
                    </td>
                </tr>
                <tr>
                    <td>
                         
                    </td>
                    <td>
                        <input type="submit" name="Search" value="Search" />
                    </td>
                </tr>
            </table>
            <% } Html.EndForm();  %>
            <!-- RENDERS PARTIAL VIEW TO DISPLAY GRID WITH SEARCH RESULTS -->
            <% Html.RenderAction("SearchView", ViewData["catalystItems"]); %>
            <br />
        </center>
    </div>
    <div class="pager">

       <% if (Model.PagingInfo != null)
          { %>
        <%: Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new { page = x, manufactureName = Model.catalystFilter.Manufacture, description = Model.catalystFilter.DescriptionFilter, manufacturePartNumber = Model.catalystFilter.ManufacturePartNumberFilter }))%>
        <% } %>
    </div>

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
</asp:Content>


SearchView:

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CINet.Areas.CatalystSearch.Models.Entities.CatalystModel>" %>
<%@ Import Namespace="CINet.Areas.CatalystSearch.HtmlHelpers" %>
<%@ Import Namespace="CINet.Areas.CatalystSearch.Models" %>

 <div>
    <% if (Model.catalystItems != null)
       { %>
        <table class="CatalystTableSpacer">
            <tr>
                <td>
                    Contract Price
                </td>
                <td>
                    Description
                </td>
                <td>
                    Manufacture Name
                </td>
                <td>
                    Manufacture Part Number
                </td>
                <td>
                    MSRP Price
                </td>
                <td>
                    Quantity Available
                </td>

            </tr>
            <% foreach (var items in Model.catalystItems)
               {%>
            <tr>
                <td>
                    <%: items.ContractPrice%>
                </td>
                <td>
                    <%: items.Description%>
                </td>
                <td>
                    <%: items.ManufactureName%>
                </td>
                <td>
                    <%: items.ManufacturePartNumber%>
                </td>
                <td>
                   <%: items.MSRPrice%>
                </td>
                <td>
                    <%: items.QuantityAvailable%>
                </td>

            </tr>
            <% }
       }

                %>
            </table>

           </div>

CatalystModel

   using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CINet.Areas.CatalystSearch.Models.Entities;
using System.ComponentModel.DataAnnotations;
using CINet.Areas.CatalystSearch.Models.Repository;
using CINet.Areas.CatalystSearch.Models.Interfaces;

namespace CINet.Areas.CatalystSearch.Models.Entities
{
    public class CatalystModel
    {

          #region PRIVATE FIELDS

        private string _connectionString = "Data Source=se-cinet-dev;Initial Catalog=cinet;User ID=sa;Password=Carouse1"; // connection string for SQL
        private ICatalystRepository _repository = null;

        #endregion
    #region PUBLIC PROPERTIES

    public IList<CatalystItem> catalystItems { get; set; }
    public PagingInfo PagingInfo { get; set; }
    public CatalystFilter catalystFilter { get; set; }
    public SelectList Manufactures { get; set; }
    public SelectList Categories { get; set; }

    [Required]
    public string ManufactureName { get; set; }

    public string Description { get; set; }

    public string ManufacturePartNumber { get; set; }

    #endregion


    #region CONSTRUCTOR

    /// <summary>
    /// Constructor instantiates SQL DB Connection
    /// </summary>
    public CatalystModel()
    {
        _repository = new CatalystRepository(_connectionString);
     //   Manufactures = GetAllManufactures();
    }



    #endregion

    #region PUBLIC GET LISTS

    /// <summary>
    /// Returns ALL Manufactures in Database
    /// </summary>
    /// <returns></returns>
    public SelectList GetAllManufactures()
    {
        SelectList manufactureNameSelectList;
        List<Manufacture> manufactureTempList = new List<Manufacture>();

        // Get List from DB
        manufactureTempList = _repository.GetManufactureList();

        // PUSH LIST INTO SELECT LIST
        manufactureNameSelectList = new SelectList(manufactureTempList, "ManufactureName", "ManufactureName");

        return manufactureNameSelectList;
    }



    #endregion

}

}

The error happens in the ListView calling the SearchView:

<% Html.RenderAction("SearchView", ViewData["catalystItems"]); %>

Any help??

Actual Error:

Server Error in '/' Application.
--------------------------------------------------------------------------------

No parameterless constructor defined for this object. 
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.MissingMethodException: No parameterless constructor defined for this object.

Source Error: 


Line 53:             <!-- RENDERS PARTIAL VIEW TO DISPLAY GRID WITH SEARCH RESULTS -->
Line 54:           <%-- <% Html.RenderPartial("SearchView", ViewData["catalystItems"]); %>
Line 55:           --%> <% Html.RenderAction("SearchView", ViewData["catalystItems"]); %>
Line 56:             
Line 57:             <br />


Source File: c:\Users\gcoleman\Documents\Source Code\Sandbox\Jonathan Henk\MVC\CINet\CINet\Areas\CatalystSearch\Views\CatalystSearch\List.aspx    Line: 55 

Stack Trace: 


[MissingMethodException: No parameterless constructor defined for this object.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
   System.Activator.CreateInstance(Type type) +6
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +403
   System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +544
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +479
   System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +45
   System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +658
   System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +147
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +98
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2504
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +548
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +475
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +181
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830
   System.Web.Mvc.Controller.ExecuteCore() +136
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.Mvc.<>c__DisplayClassa.<EndProcessRequest>b__9() +44
   System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +34
   System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +76
   System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Action action) +113
   System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.EndProcessRequest(IAsyncResult result) +124
   System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1072

[HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.]
   System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +3058371
   System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +77
   System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +28
   System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +22
   System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +766
   System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +98
   System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, Object routeValues) +65
   ASP.areas_catalystsearch_views_catalystsearch_list_aspx.__RenderContent1(HtmlTextWriter __w, Control parameterContainer) in c:\Users\gcoleman\Documents\Source Code\Sandbox\Jonathan Henk\MVC\CINet\CINet\Areas\CatalystSearch\Views\CatalystSearch\List.aspx:55
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +109
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
   System.Web.UI.Control.Render(HtmlTextWriter writer) +10
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   ASP.views_shared_site_master.__Renderform1(HtmlTextWriter __w, Control parameterContainer) in c:\Users\gcoleman\Documents\Source Code\Sandbox\Jonathan Henk\MVC\CINet\CINet\Views\Shared\Site.Master:26
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +109
   System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +8820669
   System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +31
   System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +53
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +40
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
   System.Web.UI.Control.Render(HtmlTextWriter writer) +10
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
   System.Web.UI.Page.Render(HtmlTextWriter writer) +29
   System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer) +56
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3060




--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.237 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

徒留西风 2024-12-12 12:57:57

您的问题是 CatalystModel 类没有默认构造函数,因此默认模型绑定程序无法在此处实例化它:

[ChildActionOnly]
public ViewResult SearchView(CatalystModel model)
{
    return View(model);
}

也就是说,您像这样调用这样的子控制器操作:

<% Html.RenderAction("SearchView", ViewData["catalystItems"]); %>

完全没用并且完全没有带来任何价值。

为什么不直接渲染部分:

<% Html.RenderPartial("SearchView", ViewData["catalystItems"]); %>

您还应该阅读 Haacked 博客文章,以更好地理解 RenderAction 和 RenderPartial 之间的差异。

或者,如果您确实(出于某些神秘的原因)具有控制器操作,该操作采用一些没有默认构造函数作为操作参数的模型,您将需要为此类型编写自定义模型绑定程序,并指定应使用哪个自定义构造函数来实例化当然,它以及应该传递给它什么值。

Your problem is that the CatalystModel class doesn't have a default constructor so the default model binder cannot instantiate it here:

[ChildActionOnly]
public ViewResult SearchView(CatalystModel model)
{
    return View(model);
}

This being said having such a child controller action that you are invoking like this:

<% Html.RenderAction("SearchView", ViewData["catalystItems"]); %>

is totally useless and bring strictly no value.

Why don't you render the partial directly:

<% Html.RenderPartial("SearchView", ViewData["catalystItems"]); %>

You should also read the Haacked blog post to better understand the differences between RenderAction and RenderPartial.

Or if you really (for some cryptic reason) have controller actions that take some models which do not have default constructors as action parameters you will need to write a custom model binder for this type and specify which of your custom constructors should be used to instantiate it and what values should be passed to it of course.

心病无药医 2024-12-12 12:57:57

试试这个:

<% Html.RenderAction("SearchView", new { model = ViewData["catalystItems"] }); %>

Try this:

<% Html.RenderAction("SearchView", new { model = ViewData["catalystItems"] }); %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文