开发者

EditorFor + TModel

the signature for开发者_Python百科 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)?


Haven't tested this, but couldn't you do:

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

You don't necessarily need to use the variable passed into the Lambda.


Model - is the Model - the M in MVC

TModel could just as well be sdserweJJG - it's only consistently called TModel out of convention.

Within the helper method for EditorFor you will see something like:

 TValue val = expression.Compile()(htmlHelper.ViewData.Model);

this is where the extension method compiles the lambda passed in - for example the x=>x.Model.Property part - and gets back the actual Model data to use to build the actual display controls.

The Model is passed to the view when you call return View(viewModel); from your controller action.

What you are trying to do doesn't make sense because the method was designed to work with the views Model.

You can however use @Html.Editor as this will take the actual value in the way you are trying:

@Html.Editor(ViewBag.AClassOfTheOtherType)

The sourcecode for MVC is freely available to download and view - it's well worth taking the time to do so :)


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>(...) }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜