1

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.

Preston
  • 1,300
  • 1
  • 17
  • 32
  • 1
    If your loop is constructed correctly then it should be emitting the right field names automatically. Anyway, can you post the exact exception you are getting? – stephen.vakil Sep 08 '16 at 17:50
  • What is the exact error message? – Jasen Sep 08 '16 at 17:55
  • @stephen.vakil can you describe more what you mean. This is a partial view for creating new ones that I then add multiple times within the main view. I've never seen a loop in razor do that like you describe. – Preston Sep 08 '16 at 18:08
  • @Jasen CS1928: 'HtmlHelper' does not contain a definition for 'EditorFor' and the best extension method overload 'EditorExtensions.EditorFor(HtmlHelper, Expression>, string, string, object)' has some invalid arguments – Preston Sep 08 '16 at 18:08

1 Answers1

1

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" } }
)
Jasen
  • 14,030
  • 3
  • 51
  • 68
  • Thanks, even ""+ViewBag.Id didn't work I find that really strange and counter to all the standards I'm aware of. – Preston Sep 08 '16 at 18:41
  • A plain `for` loop would do much of this for you letting you do `@Html.EditorFor(m => Contacts[i])` – Jasen Sep 08 '16 at 18:45
  • please take a look here http://stackoverflow.com/questions/39398090/how-to-properly-bind-listobject-in-the-create-view-of-mvc and tell me if that would work how you are saying. – Preston Sep 08 '16 at 18:51