Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

c# - 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?dy ?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; }
        [AllowHtml]
        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">
                <label>Anotace</label>
            </div>
                <div class="col-sm-10">
                    @Html.TextAreaFor(x => x.Annotation, new { @class = "form-control", @rows = 5 })
                    @Html.ValidationMessageFor(x => x.Annotation)
                </div>
            </div>
        <div class="form-group">
            <div class="col-sm-10">
                <label>Obsah</label>
            </div>
                <div class="col-sm-10">
                    @Html.TextAreaFor(x => x.Content, new { @class = "form-control formatedText", @rows = 20 })
                    @Html.ValidationMessageFor(x => x.Content)
                </div>
            </div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"))
{
   @Html.LabelFor(g=>g.Title)
   @Html.TextBoxFor(f=>f.Title)

    <button id="addPost">Add Tag</button>
    <label>Enter tags</label>
    <div id="tags">
        <input type="text" class="tagItem" name="Tags" />
    </div>
    <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
{
    <script>
        $(function() {
            $("#addPost").click(function(e) {
                e.preventDefault();
                $(".tagItem").eq(0).clone().val("").appendTo($("#tags"));
            });
        });
    </script>
}

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.

[HttpPost]
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};
      }
      p.Tags.Add(existingTag);
    }
    db.Posts.Add(p);
    db.SaveChanges();
    return RedirectToAction("Index","Post");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...