Pablo Acuña
Pablo Acuña

Reputation: 77

create model with list of tags in ASP MVC

I have a model like this

public class Local
{  
    public int Id { get; set; }
    public string Name{ get; set; }   
    public List<string> Tags{ get; set; }
}

I need a simple view to create a model but I don't know how to pass a list of comma separated tags from the view to the controller and then save the model with the list of tags. I saw in a similar post a solution that uses text.Split(',') but my problem is that I don't know how to pass the input text to the create action. I'm using ASP MVC 4. Sorry if this is to basic but I'm new to ASP MVC. Thanks in advance.

Upvotes: 0

Views: 1041

Answers (2)

Jeremy Bell
Jeremy Bell

Reputation: 718

 // Parse the string
 string[] list = commaSeparatedListString.Split(",");

 foreach(var tag in list) {
    <input type="text" name="tags" value="@tag" />
 }

 // In controller
 // (the HTML Form will pass an array of values if there is more than one input tag with the same name)
 [HttpPost]
 public ActionResult(int id, string name, string[] tags)
 {
    // Save the tags
    // Use string.Join("," tags) to get your comma separated list back
 }

Upvotes: 0

Leon Cullens
Leon Cullens

Reputation: 12476

I'm not sure if I understand your question (it's really vague) but you can just create a ViewModel that has a string property called 'Tags' (the comma separated data), you create a form for this ViewModel (you can use Html.EditorForModel), and in your controller simply convert your ViewModel to your entity that has a list of tags by splitting the string into an array.

Upvotes: 1

Related Questions