Daniel Liuzzi
Daniel Liuzzi

Reputation: 17147

EditorTemplates/Object.cshtml using EditorFor() instead of Editor()?

I am trying to create a generic editor template that replicates Html.EditorForModel(), to later customize and build upon. Brad Wilson's template gets pretty close, but I found that it chokes when the same key exist in both ViewData (or ViewBag) and the model. For example ViewBag.Title causes problems if the view model also has a Title property.

I learned here that using strongly-type helpers (i.e. Html.EditorFor(x => x.Title) instead of Html.Editor("Title") seems to help. So I tried to modify Brad's template, but I ran into a brick wall, as nothing I tried so far has worked. I can't figure out how to use strongly-typed helpers in a context where I don't know the model type, like an editor template for example.

Is there any way to create an Object template like Brad's, but using strongly-typed helpers (i.e. LabelFor, EditorFor, ValidatorMessageFor) instead of weakly-typed ones (i.e. Label, Editor, ValidatorMessage)?

Thanks.

Upvotes: 7

Views: 2278

Answers (2)

John Gibb
John Gibb

Reputation: 10773

I solved this problem in a slightly roundabout way, by removing the ViewData right before the call to @Html.Editor and then putting it back after.

Object.cshtml:

        object oldViewData = null;
        var hasConflictingViewData = ViewData.TryGetValue(prop.PropertyName, out oldViewData);

        if (hasConflictingViewData)
        {
            ViewData.Remove(prop.PropertyName);
        }

        @Html.Editor(prop.PropertyName)

        if (hasConflictingViewData)
        {
            ViewData.Add(prop.PropertyName, oldViewData);
        }

The only other option I could think of is using a ton of reflection to call EditorFor generically with a runtime type, and pass in an expression for the pertinent property.

Upvotes: 5

Kyle
Kyle

Reputation: 1172

You can view all of the code for the new Object.shtml by going and downloading the MVC source code. I thought it was also in some common folder on your pc already but I can't remember where.

http://aspnet.codeplex.com/releases/view/58781

Upvotes: 1

Related Questions