Search code examples
asp.net-mvc-3viewrazoreditorfor

EditorFor + TModel


the signature for this very useful method states I can indicate a type:

public static MvcHtmlString EditorFor<TModel, TValue>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression
)

... the docs very understandably state that TModel is "The type of model". It must be my particular bent that this description conveys no meaning to me whatsoever. I've googled for an explanation but found zilch.

I'm in a view where @model Website.Models.Product but want to create an editor for something of a different type. I thought I could:

@Html.EditorFor(@ViewBag.AClassOfTheOtherType)

or maybe (I'm obviously guessing):

@Html.EditorFor(TheOtherType)

but that is not acceptable syntax and so I thought:

@Html.EditorFor(x => x...)

but the lambda expression seems to be bound to @model... so I thought, "ah!":

@Html.EditoFor<TheOtherType>(...)

but VS thinks the < starts an HTML tag and indicates the end of my EditorFor call (which fails).

aaaaahhhhh!

how do I do this (in case I actually need to ask)?


Solution

  • the answer is (drumroll please)... yes, one can bind the lambda expression with the type declarator. the only problem is the Visual Studio editor, which thinks one is ending the C# part and entering the HTML part with the opening < and thus disallows proper code. Solution:

    @{ Html.EditoFor<TheOtherType>(...) }