2

Is it possible to get the EditorFor method also render the label and validation for a property like the EditorForModel method does ?

Now When I use the EditorFor method for a property (for example a string), it renders only the textbox.

EDIT

Arnis I tried it out and there some problems:

The extension method should be bound on the generic HtmlHelper class. Also returning string from the helper was causing encoded html.

So I modified your code

 public static MvcHtmlString EditorWithLabel<T>(this HtmlHelper<T> h,Expression<Func<T, object>> p)
 {
      return new MvcHtmlString(string.Format("{0}: {1}", h.LabelFor(p), h.EditorFor(p)));
 } 

But the main problem is it works only with if the propert is of type string.

When the property is Decimal,Int,DateTime an excetion will be thrown.

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

2
  • I'm quite sure problem is elsewhere. Using same approach for ints, decimals, datetimes and custom types too. Commented Nov 22, 2010 at 10:57
  • Could be the problem that I'm using ASP.NET MVC 3 RC (Razor)? Commented Nov 22, 2010 at 12:54

1 Answer 1

1

I would create custom html helper (code is untested):

public string EditorWithLabel<T>(this HtmlHelper h, 
  Expression<Func<T, object>> p){
  
  return string.Format("{0}: {1}",h.LabelFor(p),h.EditorFor(p));
}

This can be achieved with templates too, but I think custom helper fits better.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.