When should I use the "Hidden text block", and when should I use the "data attribute" (html 5)?

I need to transfer some data from my controller in my opinion. This data will be used by jQuery to perform some actions. Data is a short string. I can put it in a hidden text box and access this text box value using jQuery. I could also put the data attribute in the html element that concerns the data. I wonder what would be the best way.

To name a specific case when I had to make this choice: I had a general partial view that needed to make an ajax call to update some data in the view. However, the purpose of the ajax call depends on the context of the partial view. Therefore, I am passing a link to a partial view model. Where can I store this data for jQuery to access it?

I feel that the data attribute is somehow nicer, because I feel that the purpose of the hidden input fields is more about sending the information back along with the rest of the form.

Is there any general opinion about this?

Thanks in advance.

+4
source share
2 answers

I would use only hidden form input if I planned to send data back to the server through the form. If this is not a requirement, using a data attribute can be much simpler. It does not require a form, and you can easily access the value using jQuery (or regular JavaScript) from event handlers in the corresponding element.

+4
source

Use the model and pass that model into the view. This model will contain all the necessary data. Then use this data to generate the HTML5 data-* attribute for some DOM element that you would unobtrusively use AJAXify. Example:

 <div id="someDiv" data-remote-url="@Model.SomeModelPropertyContainingTheUrl"></div> 

and then:

 var url = $('#someDiv').data('remote-url'); ... 

If you already have a form on the page that you will be AJAXifying, you can use the action attribute of this form or still a hidden field if the value is different.

+2
source

Source: https://habr.com/ru/post/1348138/


All Articles