Submit javascript dynamically added elements to controller method like Stackoverflow

北慕城南 提交于 2019-12-12 21:10:56

问题


Put it simply: I'd like to let the user to select some tags in JS and submit it to my controller. Here are my suggestions:

  • Create a hidden input for every inserted tag with naming convention like: Tag123 (123 = this tag's unique identifier) and iterate through FormCollection in my action method to find out which tags have been selected. Cons are obvious: using FormCollection instead of ViewModel and iterating through the FormCollection to get my desired data seems bad to me.
  • Create one hidden input and append every selected tag to it. This can become messy on tags deletion since I should find the right id from the input's current value and delete it. But the Pro is that I only have one element and can put it in a viewmodel to access it in controller action.
  • Curious to see if anyone knows how SO does it. They're kind of defning the standards now. Would love to know how they do it.

Thanks.


回答1:


I have a website running with the option of adding tags, much like SO.
My approach to the problem, however, led to me create one input field for each added tag, and increment a javascript index variable every time a new input is added, then making use of a ViewModel to bind a IList<TagDTO> tags { get; set; } (forms tend to get complex over time anyway, so a viewmodel is almost always a good way to go). Here is an example of the html hidden inputs created in the page:

name=tags.Index, value=0
name=tags[0].tagid, value=201
name=tags.Index, value=2
name=tags[2].tagid, value=307

This has one great advantage to me: Internationalized tags and possibly disallowing nonexistent tags.
What I mean is that every tag has an ID, and in my "Tags" table in the database there is one column for the name of this tag in each language I support. Such as:

tagid | name_ptBR   | name_en
 201  | animais     | animals
 307  | educacional | educational

This is only my approach to the problem, but it has worked out ok so far.




回答2:


Stack Overflow just has one text input field, which is enhanced with autocompletion by JavaScript. When it's sent to the server, the field is split by spaces, and the corresponding tags are looked up by name. I recommend you do that, as it's the most accessible of all the options.



来源:https://stackoverflow.com/questions/10158089/submit-javascript-dynamically-added-elements-to-controller-method-like-stackover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!