0

I am fairly new to MVC and getting what seems to be a fairly common error but can't seem to find a solution to my particular case. A partial view is causing this error when I send it a model as so:

@model Webcasting.Library.Models.StaticPageListModel

<div class="nav-main_small-screen collapse" id="navSmallScreen">
    <ul>
        @for (var i = 0; i < Model.Pages.Count; i++)
        {
            <li>@Html.DisplayFor(m => Model.Pages[i].sFriendlyUrl)</li>
        }
    </ul>
</div>

Rather than receiving a model of this type it is getting sent the model of the parent view. The partial view is added to _Layout.cshtml as so and included in all pages:

@Html.Partial("_Nav")

The model:

namespace Webcasting.Library.Models
{
    public class StaticPageListModel : MasterModel
    {
        public List<StaticPage> Pages { get; set; }

        public StaticPageListModel()
        {
            Pages = StaticPage.GetAllPages();
        }
    }
}

The controller is as follows:

namespace Webcasting.Library.Controllers
{
    public class StaticPageListController : MasterController
    {
        public ActionResult Page()
        {
            return View(new StaticPageListModel());
        }
    }
}

I have looked at this post: The model item passed into the dictionary is of type .. but this dictionary requires a model item of type And this looked promising:

@Html.Partial("_Bar", new Bar())

However, the cshtml page is unable to reference the Bar() file. Without making an instance of this model in the Main view model class how can I make an instance of Bar and pass this to the partial view?

Jess
  • 13
  • 1
  • 4
  • You have not shown the relevant code, but it seems you want to display a partial in your layout that would be generated by the `Page` method of `StaticPageListController`, in which case you use `@Html.Action("Page", "StaticPageList")` to call the server method that renders the view (`@Html.Partial()` does not call a server method) –  Aug 01 '17 at 13:11
  • Yes, the partial view is in a shared page and it's getting passed the controller of whichever view is being displayed. Would "StaticPageList" be a method in the model? I don't quite follow. – Jess Aug 01 '17 at 13:19
  • You have not explained what any of that code is. Is the view your `_Nav.cshtml` partial? What is that controller method? (and "StaticPageList" above is the name of the controller, and "Page" is the name of the method -but I'm just guessing because your question is not clear). In anycase, why can't you use `@Html.Partial("_Nav", new StaticPageListModel())` –  Aug 01 '17 at 13:23
  • This is code I inherited and for some reason doing that pops up 49 unrelated errors. I managed a hacky way around by putting the list in the master model that everything inherits from but am not happy with it. Will keep playing around. – Jess Aug 01 '17 at 13:36

0 Answers0