Preston Preston - 1 year ago 100
C# Question

Razor won't compile even though signature matches exactly for EditorFor

I am using MVC 5.2, I'm working in a partial view that I use multiple times in a view to bind to a list of objects in my view model.

In order to get it to bind properly my understanding is that the names of the html objects need to look like Model[x].Property. The only Signature I can find for EditorFor that allows me to do this while maintaining ability to add html attributes is

public static MvcHtmlString EditorFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression,
string templateName,
string htmlFieldName,
object additionalViewData

My problem is if I try to concatenate anything in the htmlFieldName field it tells me there are invalid arguments. If I use a plain string with not concatenation, works fine. I have tried all types of concatenation, below is 1 example I've tried.

@Html.EditorFor(model => model.Name,"", @String.Format("Contacts[{0}].Name",ViewBag.Id), new { htmlAttributes = new { @class = "form-control" } })

HtmlHelper' does not contain a definition for 'EditorFor' and the best extension method overload 'EditorExtensions.EditorFor(HtmlHelper, Expression>, string, string, object)

Am I trying to accomplish this in the wrong way? Is there a better way to bind to a list of objects? Also how do I maintain things like regex validation, it doesn't seem to work anymore once I change the name.

Answer Source

Casting the dynamic ViewBag.Id satisfies the Razor compiler and the error goes away.

@Html.EditorFor(model => model.Name,
    String.Format("Contacts[{0}].Name", ViewBag.Id as string),
    new { htmlAttributes = new { @class = "form-control" } }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download