Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6347381
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T21:12:10+00:00 2026-05-24T21:12:10+00:00

My current problem is that I have a partial view that I want to

  • 0

My current problem is that I have a partial view that I want to determine what model is being used by it.

I have had to deal with a few strange scenarios for my project so I will try to outline it here, maybe someone can offer a better way to do this.

I am designing something like the Google iGoogle page. A main page with multiple widgets that are able to move around or be configured as needed. The current system loads the actual widget’s data asynchronously view a POST to a controller within my application. That controller will either render a partial view to HTML that can be returned (and then loaded into the page view JQUERY) or just straight HTML/JavaScript that is stored in a database.

This was working fine for me, I had a model for the widgets that holds a dictionary of options that are described via the database, and then used by the partial view. The problem came when I wanted to pass data to a partial view. The best solution I could come up with was having the controller determine which model the partial view in question uses, have some function that will fill the model, and then pass it, along with the partial view, to the function that will render it to HTML within the controller.

I realize this is an odd scenario for MVC (the layers are blending…) and any advice on fundamental design, or implementation of this would be greatly appreciated.

I am currently using MVC3/Razor. Feel free to ask any other questions.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T21:12:12+00:00Added an answer on May 24, 2026 at 9:12 pm

    I prototyped a possible solution to this, because it seemed like a fun problem. I hope it’s useful to you.

    Models

    First, the models. I decided to create two ‘widgets’, one for news, and one for a clock.

    public class NewsModel
    {
        public string[] Headlines { get; set; }
    
        public NewsModel(params string[] headlines)
        {
            Headlines = headlines;
        }
    }
    
    public class ClockModel
    {
        public DateTime Now { get; set; }
    
        public ClockModel(DateTime now)
        {
            Now = now;
        }
    }
    

    Controller

    My controller doesn’t know anything about the views. What it does is returns a single model, but that model has the ability to dynamically fetch the right model as required by the view.

    public ActionResult Show(string widgetName)
    {
        var selector = new ModelSelector();
        selector.WhenRendering<ClockModel>(() => new ClockModel(DateTime.Now));
        selector.WhenRendering<NewsModel>(() => new NewsModel("Headline 1", "Headline 2", "Headline 3"));
        return PartialView(widgetName, selector);
    }
    

    Delegates are used so that the correct model is only created/fetched if it is actually used.

    ModelSelector

    The ModelSelector that the controller uses is pretty simple – it just keeps a bag of delegates to create each model type:

    public class ModelSelector
    {
        private readonly Dictionary<Type, Func<object>> modelLookup = new Dictionary<Type, Func<object>>();
    
        public void WhenRendering<T>(Func<object> getter)
        {
            modelLookup.Add(typeof(T), getter);
        }
    
        public object GetModel(Type modelType)
        {
            if (!modelLookup.ContainsKey(modelType))
            {
                throw new KeyNotFoundException(string.Format("A provider for the model type '{0}' was not provided", modelType.FullName));
            }
    
            return modelLookup[modelType]();
        }
    }
    

    The Views – Simple solution

    Now, the easiest way to implement a view would be:

    @model MvcApplication2.ModelSelector
    @using MvcApplication2.Models
    @{
        var clock = (ClockModel) Model.GetModel(typeof (ClockModel));
    }
    
    <h2>The time is: @clock.Now</h2>
    

    You could end here and use this approach.

    The Views – Better solution

    That’s pretty ugly. I wanted my views to look like this:

    @model MvcApplication2.Models.ClockModel
    <h2>Clock</h2>
    @Model.Now
    

    And

    @model MvcApplication2.Models.NewsModel
    <h2>News Widget</h2>
    @foreach (var headline in Model.Headlines)
    {
        <h3>@headline</h3>
    }
    

    To make this work, I had to create a custom view engine.

    Custom view engine

    When a Razor view is compiled, it inherits a ViewPage<T>, where T is the @model. So we can use reflection to figure out what type the view wanted, and select it.

    public class ModelSelectorEnabledRazorViewEngine : RazorViewEngine
    {
        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            var result = base.CreateView(controllerContext, viewPath, masterPath);
    
            if (result == null)
                return null;
    
            return new CustomRazorView((RazorView) result);
        }
    
        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            var result = base.CreatePartialView(controllerContext, partialPath);
    
            if (result == null)
                return null;
    
            return new CustomRazorView((RazorView)result);
        }
    
        public class CustomRazorView : IView
        {
            private readonly RazorView view;
    
            public CustomRazorView(RazorView view)
            {
                this.view = view;
            }
    
            public void Render(ViewContext viewContext, TextWriter writer)
            {
                var modelSelector = viewContext.ViewData.Model as ModelSelector;
                if (modelSelector == null)
                {
                    // This is not a widget, so fall back to stock-standard MVC/Razor rendering
                    view.Render(viewContext, writer);
                    return;
                }
    
                // We need to work out what @model is on the view, so that we can pass the correct model to it. 
                // We can do this by using reflection over the compiled views, since Razor views implement a 
                // ViewPage<T>, where T is the @model value. 
                var compiledViewType = BuildManager.GetCompiledType(view.ViewPath);
                var baseType = compiledViewType.BaseType;
                if (baseType == null || !baseType.IsGenericType)
                {
                    throw new Exception(string.Format("When the view '{0}' was compiled, the resulting type was '{1}', with base type '{2}'. I expected a base type with a single generic argument; I don't know how to handle this type.", view.ViewPath, compiledViewType, baseType));
                }
    
                // This will be the value of @model
                var modelType = baseType.GetGenericArguments()[0];
                if (modelType == typeof(object))
                {
                    // When no @model is set, the result is a ViewPage<object>
                    throw new Exception(string.Format("The view '{0}' needs to include the @model directive to specify the model type. Did you forget to include an @model line?", view.ViewPath));                    
                }
    
                var model = modelSelector.GetModel(modelType);
    
                // Switch the current model from the ModelSelector to the value of @model
                viewContext.ViewData.Model = model;
    
                view.Render(viewContext, writer);
            }
        }
    }
    

    The view engine is registered by putting this in Global.asax.cs:

    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new ModelSelectorEnabledRazorViewEngine());
    

    Rendering

    My home view includes the following lines to test it all out:

    @Html.Action("Show", "Widget", new { widgetName = "Clock" })
    @Html.Action("Show", "Widget", new { widgetName = "News" })
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Scenario: I have a partial view that is used in several places across my
My current problem is that I have a JFrame with a 2x2 GridLayout. And
Here is my current question: I'm guessing that my problem (described below) is being
I have a Rails form that is being used for creating and editing a
I'm trying to write a re-usable .NET Assembly that implements WCF. My current problem
I came across a problem in my current application that required fiddling with the
I want to fix the Background while only the ListFields scrolls. Current Problem: Scrolling
Problem, there's no method: bool ChangePassword(string newPassword); You have to know the current password
The following code summarizes the problem I have at the moment. My current execution
I have strange problem with sharepoint and ajax functionality. We have an UpdatePanel placed

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.