Pogasta Pogasta - 2 months ago 7x
ASP.NET (C#) Question

Strongly-typed view for model class with collection

I am trying to do something like personal blog and i encountered a problem. I have strongly typed form for edit of my article. I am able to update simple columns like title, content, ... But I have no idea how to handle collection of tags which is mapped as many-to-many collection. What is the best practice here? Can i use some HTML helper like those for simple columns? Or need I to create a new collection everytime? Honestly I have no idea.

Model class

public class Post : IEntity
public virtual int Id{ get; set; }

[Required(ErrorMessage = "Každý článek musí mít titulek")]
[MaxLength(250, ErrorMessage ="Nadpis může mít maximálně 250 znaků")]
public virtual string Title { get; set; }
public virtual string Annotation { get; set; }
public virtual string Content { get; set; }
public virtual User Author { get; set; }
public virtual DateTime CreationDate { get; set; }
public virtual Rating Rating { get; set; }
public virtual string PreviewImageName { get; set; }
public virtual string ContentImageName { get; set; }
public virtual Category Category { get; set; }

public virtual IList<Tag> Tags { get; set; }
public virtual IList<BlogImage>Gallery { get; set; }

So far i was able to do all CRUDs with html helpers like these.

<div class="form-group">
<div class="col-sm-10">
<div class="col-sm-10">
@Html.TextAreaFor(x => x.Annotation, new { @class = "form-control", @rows = 5 })
@Html.ValidationMessageFor(x => x.Annotation)
<div class="form-group">
<div class="col-sm-10">
<div class="col-sm-10">
@Html.TextAreaFor(x => x.Content, new { @class = "form-control formatedText", @rows = 20 })
@Html.ValidationMessageFor(x => x.Content)


You basically need to use some client side javascript to make intuitive user interface to handle this collection properties which user adds. It could be one item or 100 items.

Here is a very simple way of doing it which allows user to enter each tag for the post in a textbox. user will be able to dynamically add a textbox to enter a tag name for the post.

Assuming you have a view model like this for your post creation.

public class PostViewModel
   public int Id { set; get; }
   public string Title { get; set; }
   public List<string> Tags { set; get; }

Your view will be strongly typed to this view model

@model PostViewModel
<h2>Create Post</h2>
@using (Html.BeginForm("Create","Post"))

    <button id="addPost">Add Tag</button>
    <label>Enter tags</label>
    <div id="tags">
        <input type="text" class="tagItem" name="Tags" />
    <input type="submit"/>

You can see that i have a div with one input element for the tag and a button to add tag. So now we have to listen to the click event on this button and create a copy of the textbox and add it to the dom so user can enter a second tag name. Add this javascript code to your page

@section scripts
        $(function() {
            $("#addPost").click(function(e) {

The code is self explanatory. When the button is clicked, it clone the textbox for tag name entry and add it to our container div.

Now when you submit the form, the Tags property will be filled with the tag names user entered in those textboxes. Now you just need to read the values posted and save that to the database.

public ActionResult Create(PostViewModel model)
   var p = new Post { Title = model.Title };
   //Assign other properties as needed (Ex : content etc)
   p.Tags = new List<Tag>();  
   var tags = db.Tags;
   foreach (var item in model.Tags)
      var existingTag = tags.FirstOrDefault(f => f.Name == item);
      if (existingTag == null)
        existingTag = new Tag {Name = item};
    return RedirectToAction("Index","Post");