ddeamaral
ddeamaral

Reputation: 1443

Html Helpers collection to string

I am coming across an error, trying to do something similar to this

     @Html.TextAreaFor(m => String.Join(",", Model.Tags), new { @class = "form-control" })

I can't do this. What is the correct way to make the list of strings output as desired.

UPDATE: Sorry, I am curious as to why I am unable to use a strongly typed version of an html helper, for joining a list of strings to a textbox value? For example, tags contains "mvc", "css" and "code" . I want the textbox to be prepopulated with the list as a list of strings.

Upvotes: 0

Views: 162

Answers (2)

halit
halit

Reputation: 1128

If you set your model.Tags property as a String. Split by comma in the controller.

if (!string.IsNullOrEmpty(model.Tags))
                {

                    string[] _tags={};
                    if (model.Tags.Contains(","))
                    {
                        _tags = model.Tags.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    }
                    else _tags =new[]{ model.Tags};


                    // Use _tags to save Db.
                }

On Preview/Edit Screen :

mymodel.Tags = string.Join(",",_data.Tags.Select(m => m.Tag));
return mymodel;

Upvotes: 0

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107566

I think you might be using the wrong helper -- the one you're trying to use is expecting an expression that represents a member of the model class, and also isn't meant to have a value given to it (it uses the property value). Try a different helper method, one that takes the element name, value, and html attributes:

@Html.TextArea("elementName", String.Join(", ", Model.Tags), new { @class = "form-control" })

Upvotes: 1

Related Questions