具有集合的模型类的强类型视图 [英] Strongly-typed view for model class with collection

查看:67
本文介绍了具有集合的模型类的强类型视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做个人博客之类的事情,但是遇到了问题.我已强烈键入用于编辑文章的表格.我能够更新诸如标题,内容等简单列.但是我不知道如何处理映射为多对多集合的标记集合.这里的最佳做法是什么?我可以将一些HTML帮助程序用于简单的列吗?还是需要每次都创建一个新集合?老实说,我不知道.

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.

模型类

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; }
        [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; }
    }
}

到目前为止,我已经能够使用此类HTML帮助程序进行所有CRUD.

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>

推荐答案

您基本上需要使用一些客户端javascript来制作直观的用户界面,以处理用户添加的此集合属性.可能是一个项目或100个项目.

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"/>
}

您可以看到我有一个div,其中一个输入元素用于标签,一个按钮用于添加标签.因此,现在我们必须侦听此按钮上的click事件,并创建文本框的副本并将其添加到dom中,以便用户可以输入第二个标签名称.将此JavaScript代码添加到您的页面

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>
}

该代码不言自明.单击按钮后,它将克隆用于输入标签名称的文本框,并将其添加到我们的容器div中.

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.

现在,当您提交表单时,Tags属性将被用户在这些文本框中输入的标签名称填充.现在,您只需要读取发布的值并将其保存到数据库中即可.

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");
}

这篇关于具有集合的模型类的强类型视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆