Set HtmlFieldPrefix for id but not name

asp.net-mvc, razor

Solution

I had the same issue as yourself.

@{ ViewData.TemplateInfo.HtmlFieldPrefix = "Prefix"; }
@using(Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    @Html.TextBoxFor(m => m.MerchantAccount.MerchantName, new { maxlength = 29, size = 35 })<br />
    @Html.ValidationMessageFor(m => m.MerchantAccount.MerchantName)
}

Firstly, my bad idea: Use jQuery on page load to remove undesired prefix to all names.

`$('[id*="Prefix_']).each(function(i, e) {...`

What we actually ended up doing was suggested here: https://stackoverflow.com/a/1318342/4946681

Basically, on the controller you state what prefix to strip (by specifying a bind prefix in the method signature) and it's done for you automatically.

Now we can have our ID prefixes cake, and eat (bind) them, too!

Problem

Setting `ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix` will prepend all `name` and `id` attributes. I'm wondering if there is a way to prefix just the `id` and leave the `name` alone. The scenario is this: A partial view is being loaded by AJAX multiple times on a page. A JavaScript library we are using requires the use of `id`s but we also want to be able to post the forms (so the `name`s need to match the server model). Our current solution is to generate a unique number for each time the partial view is loaded, set the `HtmlFieldPrefix` to `items[n]` (where `n` is the generated number) and for our action to recieve an array of `items` (where we only need to receive one). This gives us a globally unique `id` and a `name` which can be parsed by the model binder. This feels ugly, though. Any suggestions?

Original source

Related problems