When should I use a & ldquo; Hidden TextBox & rdquo; and when to use one (html 5) & ldquo; data-attribute & rdquo;

advertisements

I need to pass some data from my controller to my view. This data will be used by jQuery to do some stuff. The data is a short string. I could put it in a hidden text box and access that text box's value using jQuery. I could also put a data-attribute on the html element which the data concerns. I wonder what would be the best way.

To name a specific case where I had to make this choice: I had a generic partial view which needs to do an ajax call to update some data on the view. However, the destination of the ajax call is dependent on the context of the partial view. Hence I pass a link to the partial view's view model. Where do I store this data for jQuery to access it?

I feel that the data-attribute is somehow nicer because I feel the purpose of hidden input fields has more to do with posting information back together with the rest of the form.

Is there a general consensus about this?

Thanks in advance.


I would only use a hidden form input if I was planning on sending the data back to the server via a form. If that's not a requirement, using a data attribute can be much simpler. It doesn't require a form, and you can access the value more easily via jQuery (or plain JavaScript) from event handlers on the element in question.