Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I find it a bit odd in ASP.NET MVC that the Html helper extensions, like Html.EditorFor, take a Func<T1, TResult> where the T1 argument is just the already in scope Model variable, e.g.:

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

If I really wanted Model renamed, I would just assign it once to a variable in the top of the razor view. So, I feel compelled to do the following:

@Html.EditorFor(_ => Model.Name)

Does this seem reasonable?

share|improve this question
up vote 1 down vote accepted

I'd fail this review if I saw it at my company. Most are probably shown the first approach, doing this will only confuse people that come after you. Now they have to determine if the way you've chosen is actually equivolent to the "standard" way. I actually just went through that exercise myself.

share|improve this answer
    
Fair enough - not worth making others have to analyze my deviation from the standard pattern. – Stephen Swensen Jan 22 '12 at 16:45

You don't have to use x as the parameter name for the lambda. You can call it model with a small m for instance.

@Html.EditorFor(model => model.Name)

You aren't renaming it either, you're naming the parameter for the anonymous function the lambda expression represents.

But if you don't like the lambda syntax, there's also overloads taking the property name as a string.

@Html.Editor("Name")

I wouldn't presume the metadata information gathered from reflection as mentioned by w0lf will be handled completely if you reference the Model property directly from the lambdas.

share|improve this answer

I think MVC's way of suggesting that it needs a direct member of the Model class.

What (I think) MVC is doing in the x => x.Name case is analyze the expression and make sure its composed of a single node, which is a property/field of the input parameter (no need to check if the property/field belongs to the Model class, since this is strongly typed in the expression itself)

So, basically MVC takes a reference to a member of the Model class. After doing so, it uses the Name of the member to generate the for attribute of the HTML element and the Value of the member for the current Model instance to do the actual display (using reflection, probably).

Using the second approach it might still be possible, but more indirect, because when parsing the Lambda expression, it should also check that the Model variable is an instance of the Model class, in addition to all the other things it needs to do.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.