Inx
Inx

Reputation: 2384

PartialView as HtmlHelper?

Ok.. here we go.. the weirdest and most confusing question of the month :) I would like to create a HtmlHelper that some how renders html, but uses a partial view for its template of how the html should be rendered, so to put it more simple.. I would like to do exactly the same as a "normal" Controller and view does.. get some data, pass it to the view and then render the html, but in this case I would like to pass some data to a partial view, and then get the returned html as a string and then return that html from a HtmlHelper method... In this way I would like to be able to write for instance @Html.HeadMenu, that then would return the html for the headmenu, but I would also be able to at anytime without recompiling be able to change the html.. since its all in a partial view.. and I wont have to worry about any server-side things.. and I will also get the benefit of the intellisense since my method will show up in @Html.

I hope you will understand this..since its kind of hard to explain..

Thanks in advance!

Upvotes: 0

Views: 814

Answers (3)

archil
archil

Reputation: 39491

I would do it this way

Define data that you imagine to pass to your htmlhelper

public class HeadMenuViewModel
{
    public string SomeProperty {get;set;}
}

Define view named HeadMenuViewModel.cshtml in Views/Shared/DisplayTemplates

@model HeadMenuViewModel
<div>
 ////
</div>

From now, you can display your data using

@Html.DisplayFor(model => model.HeadMenu)

And you could write named shortcut-extension for it

    using System.Web.Mvc.Html;
...
    public static MvcHtmlString HeadMenu<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
       return helper.DisplayFor(expression);
    }

Now, change your HeadMenuViewModel.cshtml everytime you need to

Upvotes: 0

DavidWainwright
DavidWainwright

Reputation: 2935

You could be looking for the Html.RenderAction(actionName, controllerName, routeValues) method.

Upvotes: 1

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

How about the Partial HTML-extension method, it sounds like what you are trying to achive right?

@{
var htmlString = Html.Partial("YourPartialViewName").ToString();
}

It also has an overload so that you can pass a model to the partial view:

@{
var htmlString = Html.Partial("YourPartialViewName", partialViewModel).ToString();
}

Upvotes: 1

Related Questions