Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set HtmlFieldPrefix for id but not name

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 ids but we also want to be able to post the forms (so the names 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?

like image 560
jaypeagi Avatar asked Oct 21 '22 05:10

jaypeagi


1 Answers

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!

like image 133
Nate Avatar answered Nov 03 '22 23:11

Nate