Dav-id
Dav-id

Reputation: 1

Overriding EditorFor ID field within nested EditorFor

Hi I am trying to explicitly change the ID and Name and Validate-For fields in my EditorFor outputs.

I have the following code:

Html.EditorFor(x => ViewBag.NestedFormDatas)

The above prefixes all of the fields with the name of the current Model.

My temporary solution is the following (I know it is far from ideal but it works!):

@Html.Raw(Html.EditorFor(x => ViewBag.NestedFormDatas).ToHtmlString().Replace("NestedForm", "DesiredPrefix"))

Upvotes: 0

Views: 1332

Answers (2)

Paweł Staniec
Paweł Staniec

Reputation: 3181

You most certainly may try to utilize htmlAttributes argument for overriding html properties with TextBoxFor :

@Html.TextBoxFor(x=>item.Name,new { id="newId"})

The concern I'm having looking at your code is that you're using dynamic view data dictionary (ViewBag) with a method that was meant for object properites of known type. I would strongly advise to replace ViewBag with a ViewModel having strongly typed collection. That would solve your problem with field naming ( I only assume, but that's the only thing I could think of as a reason for removing prefix from your input elements)

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

I suspect that you need to change the id and name attributes because you are not using view models. The following seems just so wrong:

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

If you properly use view models, you don't need to changes names and ids, because the editor template will already generate proper values:

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

Anyway, one possibility is to write a custom editor template for the given type. So if we suppose that NestedFormDatas is a string type you could add the following ~/Views/Shared/EditorTemplates/String.cshtml editor template to override the default one and allow you to specify additional attributes:

@Html.TextBox(
    "", 
    ViewData.TemplateInfo.FormattedModelValue,
    ViewData
)

and then:

@Html.EditorFor(x => x.NestedFormDatas, new { id = "foo" })

As far as the name attribute is concerned, this is not something that could be overriden with the TextBox helper. You will have to write your own helper if you ever needed to achieve that. But as I said if you use view models you never need to do that because that's exactly the purpose of view models: their are specifically defined to match the requirements of the given view.

So get rid of any traces of ViewBag in your code and start defining view models. You will see how much more fun and easy ASP.NET MVC will become.

Upvotes: 2

Related Questions