This may be a bit moot, but it is something I want to do just for the sake of seeing how, and I think it is a little cleaner than the typical method.
Right now, I can pass extra ViewData to a partial view like this;
@Html.Partial( "path/to/partial", new ViewDataDictionary{{ "key", "value" }})
And that works fine, though I was wondering, would it be possible to make an extension method that would just clean it up a bit? I've tried to do it for a few hours now and am finding myself a bit lost, but I am attempting to go the route of ..
@Html.Partial( "path/to/partial" ).With("key","data").With("key2","data2")
So basically, it's just syntax sugar. But I haven't been able to get this to work. Has anyone else achieved something similar?
Update
I actually may have solved this myself. I had to turn the idea upside down to get the result I want. I'm not sure if I'll even use it, given how obtuse it is, but it was interesting to learn about! I am very welcoming to any insight that could be used to make this better. But essentially, the trick was to do it in reverse.
using System;
namespace System.Web.Mvc.Html {
public static partial class PartialViewExtensions {
/// <summary>
/// An Html Helper specifically for rendering a partial view with a fluently declared ViewDataDictionary.
/// </summary>
public class PartialHtmlHelper : HtmlHelper
{
public PartialHtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)
: base(viewContext, viewDataContainer) { }
}
/// <summary>
/// Prepare the upcoming partial view with view data.
/// </summary>
public static PartialHtmlHelper With( this HtmlHelper helper, string key, dynamic value ) {
var partial = new PartialHtmlHelper( helper.ViewContext, helper.ViewDataContainer );
partial.ViewData.Add( key, value );
return partial;
}
/// <summary>
/// Prepare the upcoming partial view with view data.
/// </summary>
public static PartialHtmlHelper With( this PartialHtmlHelper helper, string key, dynamic value ) {
helper.ViewData.Add( key, value ); return helper;
}
/// <summary>
/// Render a prepared partial view with readied view data.
/// </summary>
public static MvcHtmlString Using( this PartialHtmlHelper helper, string partialViewName ) {
return helper.Partial( partialViewName, helper.ViewData );
}
}
}
And that makes it very easy to declare with fluent, chained methods.
@Html
.With("alpha", "alpha.property" )
.With("beta", "beta.property" )
.With("gamma", "gamma.property")
.With("epsilon", DateTime.UtcNow() )
.With("sigma", "sigma.property" )
.Using("Templates/Form/Slots")
With()method.Withmethod yet. I'm still stuck trying to figure out what to attach it to. I thought attaching it toMvcHtmlStringwould work, but that doesn't seem to behave like I thought.MvcHtmlStringclass hierarchy doesn't contain much functionality that will help you here (all it appears to do is give you aToHtmlString()method). You might be better off writing your ownPartial()extension method, wrapping one of the existingPartial()methods.