Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top