Search code examples
htmlasp.net-mvcviewusercontrol

Getting a Partial View's HTML from inside of the controller


I have developed a simple mechanism for my mvc website to pull in html via jquery which then populates a specified div. All is well and it looks cool.
My problem is that i'm now creating html markup inside of my controller (Which is very easy to do in VB.net btw) I'd rather not mix up the sepparation of concerns.

Is it possible to use a custom 'MVC View User Control' to suit this need? Can I create an instance of a control, pass in the model data and render to html? It would then be a simple matter of rendering and passing back to the calling browser.


Solution

  • You have several options.

    Create a MVC View User Control and action handler in your controller for the view. To render the view use

    <% Html.RenderPartial("MyControl") %>
    

    In this case your action handler will need to pass the model data to the view

    public ActionResult MyControl ()
    {
        // get modelData
    
        render View (modelData);
    }
    

    Your other option is to pass the model data from the parent page. In this case you do not need an action handler and the model type is the same as the parent:

    <% Html.RenderPartial("MyControl", ViewData.Model) %>
    

    If your user control has it's own data type you can also construct it within the page

    In MyControl.ascx.cs:

    public class MyControlViewData
    {
        public string Name { get; set; }
        public string Email { get; set; }
    }
    
    public partial class MyControl : System.Web.Mvc.ViewUserControl <MyControlViewData>
    {
    }
    

    And in your page you can initialize your control's data model:

    <% Html.RenderPartial("MyControl", new MyControlViewData ()
       {
            Name= ViewData.Model.FirstName,
            Email = ViewData.Model.Email,
       });
     %>