This project is read-only.

DataGrid prefixedId command in Insert

Nov 4, 2011 at 6:06 AM


I'm using a script in the Edit template of the datagrid so that when you click the Add button it fires and does some things on the newly inserted row.  However I am noticing that when I get the prefixed Id for an item it is getting the wrong row Id.  It seems to be 1 above what it should be.

As an example I want to focus the first item in a grid when you click Add.

I put this script in the edit template:

<script type="text/javascript">


 $('#@Html.PrefixedId(m=>m.Portfolio)').focus  ();




 However it doesn't work.  If however I do some code to get the prior row id it does.

var id = '@Html.PrefixedId(m => m.Portfolio)'.match(/[0-9]/) * 1 - 1;

$('#PortfolioAllocations___' + id + '___Item_Value_Portfolio').focus();

But this means I have to hard code in the link.

Is there any reason why what I'm doing isn't working?



Nov 4, 2011 at 10:34 AM
Edited Nov 4, 2011 at 10:40 AM

Is there any reason why what I'm doing isn't working?

YES! You are assuming that the new Html of the row is created when you click the add button. THIS IS FALSE. This is true for the TreeView and the SortableListFor, but it is false for the Datagrid! Due to the way its changes tracking capabilities are implemented new rows are NOT CREATED when you click add. Normally when you do this an already exixting row is used, then if there is no other old row to use for a possible next add operation a new one is "prepared", otherwise an hold one is "reserved" for the next add. That is appear to work when you go back on the previous item...because the javascript you triggers is the one of the row that is prepared for the bnext add...not the one that is currently added. 

As a conclusion scripts in the row can be used JUST TO INITIALIZE THE ROW, for instance by attaching a jQueryUI plugin to some Html not for preparing them to be used (ie focus()).



Starting from release 1.4 I implemented events for all items controls. See here: 

You need to bind an handle that do the focus operation on the "ItemCreated" case and maybe also in the  "ItemGoneEdit" case. In both cases you are passed the involved row. You can add a css attribute to your portfolio textbox and then do $('.MyPortfolio', item).focus() where item is the item you het as argument of the event (see the docs for details). See docs examplkes and the new BinariesWithSimpleExamples to see how to attach events to the grid. 

Nov 6, 2011 at 7:57 PM

OK, thanks.  I realised I was a bit behind in the versions of the toolkit.  Have upgraded to the latest and implemented the itemChanged event.  Thanks.