开发者

When should I use a "Hidden TextBox" and when should a use a (html 5) "data-attribute"?

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.


Use a model and pass this model to the view. This model will contain all the necessary data. Then exploit this data to generate an HTML5 data-* attribute to some DOM element which you would unobtrusively 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 could use the action attribute of this form or yet a hidden field if the value is different.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜