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");
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…