locked
The model item passed into the dictionary is of type 'CMSFC.Models.Page', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[CMSFC.Models.PageConfig]'. RRS feed

  • Question

  • User-366701151 posted

    This is the Details2 view (main view):

    <pre>@model CMSFC.Models.Page

    @{

    Layout = "~/Views/Shared/_Layout.cshtml";

    }
    </pre><pre> var a = Html.Partial("~/Views/Pages/ViewTest.cshtml");
    string s = Model.Template.ToString();
    s.Replace("@section test{}", a.ToString());


    @Html.Raw(s);

    }
    </pre>


    This is its controller:

    <pre>using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using CMSFC.Models;
    using System.IO;

    namespace CMSFC.Controllers
    {
    public class PagesController : Controller
    {
    private CMSFCEntities2 db = new CMSFCEntities2();

    // GET: Pages
    public ActionResult Index()
    {
    return View(db.Pages.ToList());
    }


    /* public ActionResult Index2()
    {
    // CMSFCEntities2 db = new CMSFCEntities2();
    // List<Page> model = db.Pages.ToList();

    // return View(model);

    return View(db.PageConfigs.ToList().Where(m => m.PageId == "Page").ToList());


    }*/


    // GET: Pages/Details/5
    public ActionResult Details(int? id)
    {
    if (id == null)
    {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Page page = db.Pages.Find(id);
    if (page == null)
    {
    return HttpNotFound();
    }
    return View(page);
    }


    // [ChildActionOnly]
    // public ActionResult ViewTest1()
    // {
    // var model = new PageConfig();

    // return PartialView("ViewTest", model);
    // }


    public ActionResult ViewTest()
    {

    return PartialView();

    }

    public ActionResult Details2(int? id)
    {
    if (id == null)
    {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Page page = db.Pages.Find(id);
    if (page == null)
    {
    return HttpNotFound();
    }

    // return View(db.PageConfigs.ToList().Where(m => m.PageId == "test").ToList());
    return View(page);


    // return View(page);
    }

    //[ChildActionOnly]
    // public ActionResult ViewTest()
    // {
    // return PartialView(db.PageConfigs.ToList());
    // }

    // public ActionResult Index()
    // {

    // return View(students);
    // @Html.Partial("_StudentList", Model)
    //}


    // public PartialViewResult ViewTest()
    // {
    // return PartialView("ViewTest" , db.PageConfigs.ToList());
    // }

    // GET: Pages/Create
    public ActionResult Create()
    {
    return View();
    }

    // POST: Pages/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Template,ShowOnMeny")] Page page)
    {
    if (ModelState.IsValid)
    {
    db.Pages.Add(page);
    db.SaveChanges();
    return RedirectToAction("Index");
    }

    return View(page);
    }

    // GET: Pages/Edit/5
    public ActionResult Edit(int? id)
    {
    if (id == null)
    {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Page page = db.Pages.Find(id);
    if (page == null)
    {
    return HttpNotFound();
    }
    return View(page);
    }

    // POST: Pages/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Template,ShowOnMeny")] Page page)
    {
    if (ModelState.IsValid)
    {
    db.Entry(page).State = EntityState.Modified;
    db.SaveChanges();
    return RedirectToAction("Index");
    }
    return View(page);
    }

    // GET: Pages/Delete/5
    public ActionResult Delete(int? id)
    {
    if (id == null)
    {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Page page = db.Pages.Find(id);
    if (page == null)
    {
    return HttpNotFound();
    }
    return View(page);
    }

    // POST: Pages/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
    Page page = db.Pages.Find(id);
    db.Pages.Remove(page);
    db.SaveChanges();
    return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
    if (disposing)
    {
    db.Dispose();
    }
    base.Dispose(disposing);
    }
    }
    }
    </pre>


    Now , what im trying to do is get a partial view into string ,partial view has another model class , like this :
    <pre>

    @model IEnumerable<CMSFC.Models.PageConfig>

    @{

    // Layout = "~/Views/Shared/_Layout2.cshtml";
    }


    @foreach (var module in Model)
    {
    if (module.Placeholder == "test" && module.PageId == "test")
    {
    // Html.RenderAction("NewsList", "ContentHtml")
    Html.RenderAction(module.Control, "ContentHtml", new { id = module.Content });

    // @Html.DisplayFor(modelItem => module.Control) ;


    }


    <br />
    }

    </pre>

    And im getting this error :

    <pre>The model item passed into the dictionary is of type 'CMSFC.Models.Page', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[CMSFC.Models.PageConfig]'.

    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 'CMSFC.Models.Page', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[CMSFC.Models.PageConfig]'.

    Source Error:


    Line 76:
    Line 77: // @Model.Template.Replace("@section test{}",@{ Html.RenderPartial("ViewTest"); } );
    Line 78: var a = Html.Partial("~/Views/Pages/ViewTest.cshtml");
    Line 79: string s = Model.Template.ToString();
    Line 80: s.Replace("@section test{}", a.ToString());

    Source File: S:\My Documents\Visual Studio 2015\Projects\CMSFC\CMSFC\Views\Pages\Details2.cshtml Line: 78
    </pre>

    How can i load a partial view , that requires another model class ?!

    Friday, September 8, 2017 11:59 AM

All replies

  • User475983607 posted

    The View is strongly typed and expects the a collection of CMSFC.Models.PageConfig but the action is passing a CMSFC.Models.Page.

    Friday, September 8, 2017 12:30 PM
  • User-366701151 posted

    But partial view should get data from this model class :

    @model IEnumerable<CMSFC.Models.PageConfig>
    
    Friday, September 8, 2017 12:31 PM
  • User475983607 posted

    ddgg

    But partial view should get data from this model class :

    @model IEnumerable<CMSFC.Models.PageConfig>
    

    The error is very clear.  The strongly typed view does not match the model passed by the action.

    Friday, September 8, 2017 12:33 PM
  • User-366701151 posted

    i tried another way to solve this:

        
        <script type="text/javascript">
     
            $(function(){
                var template='@Model.Template"
     
                $("#div1").load('@Url.Action("~/Views/Pages/ViewTest.cshtml")') ;
     
                template.replace("@section test{}" , $("#div1").html())
                $("#div2").html(template);
            })
     
    </script>
        
     
     
    <div id="div1" style="display:none">
     
    </div>
     
    <div id="div2">
     
    </div>



    But its not showing anything in screen.The idea is , to replace particular words from model.template with certain partil-views. Model.Template is column of Page class , and Partial Views are derived from PageConfig class.


    This is pageconfig controller :

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using CMSFC.Models;
     
    namespace CMSFC.Controllers
    {
        public class PageConfigsController : Controller
        {
            private CMSFCEntities2 db = new CMSFCEntities2();
     
     
     
     
     
     
     
     
     
     
            [HttpPost]
            public ActionResult GetModel()
            {
                var myTitle = db.PageConfigs.Select(p => p.PageId).FirstOrDefault();
                return Json(myTitle, JsonRequestBehavior.AllowGet); //pass title to View
     
            }
            //add new page
            public ActionResult AddPage()
            {
                return View();
            }
            //Show the new page
            public ActionResult NewPageTest(string pageid)
            {
                //according to the pageid to get the page information
     
                ViewBag.Content = TempData["content"].ToString();
                PageConfig config = new PageConfig();
        //        config.sideBar = (bool)TempData["sidebar"]; //pass the status of side bar to view
                return View(config);
            }
            //get input data and save in database
            [HttpPost]
            public ActionResult SubmitPage(PageConfig pageconfig)
            {
                TempData["content"= pageconfig.Content;//body
            //    TempData["sidebar"] = pageconfig.sideBar; //side bar
                db.PageConfigs.Add(pageconfig);
                db.SaveChanges();
                return Json(pageconfig.PageId, JsonRequestBehavior.AllowGet); // pass page title
            }
     
     
           // public ActionResult ViewTest()
           // {
           //     return View(db.PageConfigs.ToList().Where(m => m.PageId == "test").ToList());
          //  }
     
     
     
     
     
     
     
            public ActionResult ViewTest()
            {
     
                      return PartialView();
           //     return PartialView("ViewTest", new PageConfig());
            }
     
     
     
     
     
     
     
     
            // GET: PageConfigs
            public ActionResult Index()
            {
                return View(db.PageConfigs.ToList());
            }
     
            // GET: PageConfigs/Details/5
            public ActionResult Details(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                PageConfig pageConfig = db.PageConfigs.Find(id);
                if (pageConfig == null)
                {
                    return HttpNotFound();
                }
                return View(pageConfig);
            }
     
            // GET: PageConfigs/Create
            public ActionResult Create()
            {
                return View();
            }
     
            // POST: PageConfigs/Create
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Create([Bind(Include = "Id,PageId,Control,Content,Placeholder,NrOfRecords")]PageConfig pageConfig)
            {
                if (ModelState.IsValid)
                {
                    db.PageConfigs.Add(pageConfig);
                    db.SaveChanges();
                     return RedirectToAction("Index");
     
                  
                }
     
                return View(pageConfig);
            }
     
            // GET: PageConfigs/Edit/5
            public ActionResult Edit(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                PageConfig pageConfig = db.PageConfigs.Find(id);
                if (pageConfig == null)
                {
                    return HttpNotFound();
                }
                return View(pageConfig);
            }
     
            // POST: PageConfigs/Edit/5
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Edit([Bind(Include = "Id,PageId,Control,Content,Placeholder,NrOfRecords")]PageConfig pageConfig)
            {
                if (ModelState.IsValid)
                {
                    db.Entry(pageConfig).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                return View(pageConfig);
            }
     
            // GET: PageConfigs/Delete/5
            public ActionResult Delete(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                PageConfig pageConfig = db.PageConfigs.Find(id);
                if (pageConfig == null)
                {
                    return HttpNotFound();
                }
                return View(pageConfig);
            }
     
            // POST: PageConfigs/Delete/5
            [HttpPostActionName("Delete")]
            [ValidateAntiForgeryToken]
            public ActionResult DeleteConfirmed(int id)
            {
                PageConfig pageConfig = db.PageConfigs.Find(id);
                db.PageConfigs.Remove(pageConfig);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
     
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
        }
    }
    

     

    Friday, September 8, 2017 12:33 PM
  • User475983607 posted

    This is just wrong...

    $("#div1").load('@Url.Action("~/Views/Pages/ViewTest.cshtml")') ;

    In MVC routes resolve to an action method not a View.

    The syntax should look like this.

    $("#div1").load('@Url.Action("~/Home/ViewTest")') ;

    Friday, September 8, 2017 12:38 PM
  • User-366701151 posted

    I changed it into :

    $("#div1").load('@Url.Action("~/Pages/ViewTest")') ;
    


    now im getting same error

    The model item passed into the dictionary is of type 'CMSFC.Models.Page', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[CMSFC.Models.PageConfig]'.

    Friday, September 8, 2017 12:41 PM
  • User475983607 posted

    I changed it into :

    $("#div1").load('@Url.Action("~/Pages/ViewTest")') ;
    


    now im getting same error

    The model item passed into the dictionary is of type 'CMSFC.Models.Page', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[CMSFC.Models.PageConfig]'.

    The error message explicitly describes the problem.  The view expects a collection of CMSFC.Models.PageConfig but the controller is passing CMSFC.Models.Page.   Aside form that the posted code is very confusing to read and it seems that the posted code does not match the error.

    Post only the relevant bits and the code that is actually executing or causing the error.

    Friday, September 8, 2017 12:49 PM
  • User-366701151 posted

    This is the main view that calls the partial view :

    @model CMSFC.Models.Page
     
    @{
     
        Layout = "~/Views/Shared/_Layout.cshtml";
     
    }
        
        <script type="text/javascript">
     
            $(function(){
                var template='@Model.Template"
     
                $("#div1").load('@Url.Action("~/Pages/ViewTest")') ;
     
                template.replace("@section test{}" , $("#div1").html())
                $("#div2").html(template);
            })
     
    </script>
        
     
     
    <div id="div1" style="display:none">
     
    </div>
     
    <div id="div2">
     
    </div>
    



    This is the partial view , that uses another model class :

     
    @model IEnumerable<CMSFC.Models.PageConfig>
     
    @{
     
    //    Layout = "~/Views/Shared/_Layout2.cshtml";
    }
     
     
     
     
     
     
    @foreach (var module in Model)
    {
        if (module.Placeholder == "test" && module.PageId == "test")
        {
            //   Html.RenderAction("NewsList", "ContentHtml")
            Html.RenderAction(module.Control, "ContentHtml"new { id = module.Content });
     
     
     
            //  @Html.DisplayFor(modelItem => module.Control)   ;
     
     
        }
     
     
        <br />
    }
     
     
     
     
     
     
     
    






    These are actions from main view dealing with error:

    public ActionResult Details2(int? id)
         {
             if (id == null)
             {
                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
             }
             Page page = db.Pages.Find(id);
             if (page == null)
             {
                 return HttpNotFound();
             }
            
             //      return View(db.PageConfigs.ToList().Where(m => m.PageId == "test").ToList());
             return View(page);
     
     
           //  return View(page);
         }
    





    public ActionResult ViewTest()
         {
              //  return PartialView("ViewTest", new PageConfig());
            
              return PartialView();
     
         }




    I understand the error , but i dont know how to resolve this , i have a table Page with a column Template that stores html content , example :

    @section test{}
    <div></div>

    Now , what im trying to do is , get this html from database , model.template , and replace this piece of code , example @section test{} ,with a specific content , this specific content has to be a partial view /or something else , that reads data from PageConfig class . 


    I also tried this :

    var a = Html.Partial("~/Views/Pages/ViewTest.cshtml");
    string s = Model.Template.ToString();
    s.Replace("@section test{}", a.ToString());
     
     
    @Html.Raw(s);



    But im getting every time this same error.

    Regards.




    Friday, September 8, 2017 12:56 PM
  • User475983607 posted

    Again, it seems that you are not posting the code that goes with the error. As far as I can tell you're  doing an HTTP GET Pages/ViewTest in the browser to load HTML in the DOM. The action returns an the partial and does not pass a model.

    public ActionResult ViewTest()
    {
    	  //  return PartialView("ViewTest", new PageConfig());
    	  return PartialView();
    }

    Yet the View is trying to access model properties which should cause a different error assuming this code is from the partial View.

    @foreach (var module in Model)
    {
        if (module.Placeholder == "test" && module.PageId == "test")
        {
            //   Html.RenderAction("NewsList", "ContentHtml")
            Html.RenderAction(module.Control, "ContentHtml", new { id = module.Content });
     
     
     
            //  @Html.DisplayFor(modelItem => module.Control)   ;
     
     
        }
     
     
        <br />
    }

    Friday, September 8, 2017 1:16 PM
  • User475983607 posted

    Can you explain what problem you are trying to solve at a high level?

    Friday, September 8, 2017 1:20 PM
  • User-366701151 posted

    I have two unrelated classes , one to show news PageConfig and one page template Page.



    Page has a column Content that saves only html content example like this :

    @section test{
    }
    <div class="row" style="width:800px; margin:0 auto;">
    <div class="col-md-4" style="width:800px; margin:0 auto;">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    </div>

    Now what im trying to do is dynamically populate the page ,  look inside this html content for a certain pattern , example @section test{} , and replace this pattern with news .
    What i tried is :
    1.

     <script type="text/javascript">
     
            $(function(){
                var template='@Model.Template"
     
                $("#div1").load('@Url.Action("~/Pages/ViewTest")') ;
     
                template.replace("@section test{}" , $("#div1").html())
                $("#div2").html(template);
            })
     
    </script>
        
     
     
    <div id="div1" style="display:none">
     
    </div>
     
    <div id="div2">
     
    </div>
    

    public ActionResult ViewTest()
        {
             //  return PartialView("ViewTest", new PageConfig());
           
             return PartialView();
     
        }









    2.

    var a = Html.Partial("~/Views/Pages/ViewTest.cshtml");
             string s = Model.Template.ToString();
             s.Replace("@section test{}", a.ToString());
     
     
             @Html.Raw(s);







    3.


    Model.Template = Model.Template.Replace("@section test{}", Html.RenderPartial("~/Views/Pages/ViewTest.cshtml"));
        @Html.Raw(Model.Template);






    This is the main view :

    So I`ve created a partial view , inside the PageController , that uses PageConfig class   @model IEnumerable<CMSFC.Models.PageConfig> to extract news from it :

     
    @model IEnumerable<CMSFC.Models.PageConfig>
     
    @{
     
    //    Layout = "~/Views/Shared/_Layout2.cshtml";
    }
     
     
     
     
     
     
    @foreach (var module in Model)
    {
        if (module.Placeholder == "test" && module.PageId == "test")
        {
            //   Html.RenderAction("NewsList", "ContentHtml")
            Html.RenderAction(module.Control, "ContentHtml"new { id = module.Content });
     
     
     
            //  @Html.DisplayFor(modelItem => module.Control)   ;
     
     
        }
     
     
        <br />
    }
     
     
     
     
     
     
     
    




    Friday, September 8, 2017 1:28 PM
  • User-366701151 posted

    The idea is to populate html tags like head , body , right , left , footer , with different partial views (news).

    Friday, September 8, 2017 1:30 PM
  • User475983607 posted

    The idea is to populate html tags like head , body , right , left , footer , with different partial views (news).

    I still do not understand the problem you are trying to solve.  MVC is a framework for building dynamic HTML.   A common layout is created using HTML and CSS.  The dynamic content is stored in a database - the model.  The controller retrieves the Model and passes the Model to the View.  The View wraps the Model in HTML because that's what browsers understand.

    It seems that you trying to create a custom framework rather than using the MVC framework as intended.

    Friday, September 8, 2017 2:54 PM