Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ID of EditorFor with nested viewmodels in asp.net mvc 2

So I have two nested view models, CreditCard -> BillAddress. I have a view, "EditBilling", that has EditorFor(CreditCard). The CreditCard EditorTemplate has EditorFor(BillAddress), and the BillAddress EditorTemplate has EditorFor(BillState).

The end result is a select list with id "CreditCard_BillAddress_BillState".

I need to reference this in javascript, thus need to know the ID. In other situations, with non-nested ViewModels, I have used the following code:

$('#<%= ViewData.ModelMetadata.PropertyName %>_BillState')

The problem here is that the ModelMetadata.PropertyName property is only aware of the current property, not the parent(s). So I end up with the following:

$('#BillAddress_BillState')

How does one go about getting the client ID of nested strongly typed helpers? Thanks in advance.

like image 626
Luke Avatar asked Dec 20 '25 08:12

Luke


1 Answers

I believe I've found a solution by looking through the source code of the TemplateHelpers. It seems that ViewData.TemplateInfo.HtmlFieldPrefix yields the full "name" (basically with "." as a separator instead of "_").

like image 176
Luke Avatar answered Dec 23 '25 00:12

Luke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!