简体   繁体   English

如何以一对多关系向实体添加评论

[英]How to add a Comment to an entity in a one-to-many relationship

This is the scenario dumbed down: 这是愚蠢的情况:

I have a class Device 我有一个Device

[Key]
public int Id { get; set; }
[MaxLength(50)]
public String Name { get; set; }
[Required]
public Category Category { get; set; }
[Required]
public Manufactor Manufactor { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<Status> Status { get; set; }

And a class Comment 和A类Comment

public int ID { get; set; }
public string Content { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateCreated { get; set; }
public string Author { get; set; }
public virtual Device Device { get; set; }

As you can see an entity of device can have many comments, but one comment only has one device. 如您所见,设备的实体可以有很多注释,但是一个注释只有一个设备。

In my controller I have these two actions: 在我的控制器中,我有以下两个操作:

    public ActionResult AddComment(int id)
    {
        Device device = db.Devices.Include(x => x.Comments).Where(dev => dev.Id == id).FirstOrDefault();
        if (device == null)
        {
            return HttpNotFound();
        }
        return View(device);
    }

    [HttpPost, ActionName("CommentAdded")]
    public ActionResult CommentAdded(int id)
    {
        Device device = db.Devices.Find(id);
        db.Entry(device).State = EntityState.Modified;
        db.Devices.AddOrUpdate(device);

        foreach(var comment in device.Comments)
        {
            db.Comments.AddOrUpdate(comment);
        }

        db.SaveChanges();

        return View("Index");
    }

Up to this point everything seemed straight forward. 到目前为止,一切似乎都是直截了当的。 But suddently I don't know how to create a view in which I can do these 3 things: 但是突然之间,我不知道如何创建一个视图,在其中可以执行以下三件事:

  1. Display Name of the device 设备的显示名称
  2. Display all comments 显示所有评论
  3. Display a textfield to add another comment 显示文本字段以添加其他评论

I can easily achieve 1 and 2 but I have no idea on how to add another comment and then submit the form. 我可以轻松实现1和2,但是我不知道如何添加其他评论然后提交表单。

AddComment.cshtml: AddComment.cshtml:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Device</h4>
        <hr />
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.DisplayFor(model => model.Name)
            </div>
            <div class="col-md-6">
            <br/>
            <div class="row">
                @Html.EditorFor(model => model.Comments)

            </div>
            @foreach (var comment in Model.Comments)
            {
                <div class="row">
                    <div class="col-md-4">
                        <strong>
                            @Html.DisplayFor(model => comment.Author)
                        </strong>
                    </div>
                    <div class="col-md-4">
                        <strong>
                            @Html.DisplayFor(model => comment.DateCreated)
                        </strong>
                    </div>
                    <div class="col-md-4">

                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <p>
                            @Html.DisplayFor(model => comment.Content)
                        </p>
                    </div>
                </div>

            }
        </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

The problem at hand is: what do I need to change in my view (pos. controller), to be able to add another comment to the device selected? 当前的问题是:我需要在视图(位置控制器)中进行哪些更改才能向所选设备添加其他注释?

Something along these lines. 遵循这些原则。 Just need create a html form and map the form fields to the ajax function. 只需创建一个html表单并将表单字段映射到ajax函数。 then call the function when the form is submitted. 然后在提交表单时调用该函数。

hopefully that helps. 希望有帮助。

[HttpPost]
public ActionResult AddComment(int id,Comment comment)
{
    Device device = db.Devices.Find(id);
    comment.DateCreated = DateTime.Now;
    Device.Comment.Add(comment);
    db.Entry(device).State = EntityState.Modified;

    db.saveChanges();


    return Json("Success");
}


$.ajax({
        type: "POST",
        url: "/AddComment",
        data: { Id: '@Html.IdFor(m => m.Id)', 
        Comment: { Content: 'data',    Author: 'Author'} },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
        if (data == "Success") {
           $('#COMMENTSDIV').append(" YOUR COMMENTS MARKUP HERE ");
            }
        }
       });

You just need to wrap the add comment functionality in the form and post that back to the server with a corresponding action. 您只需要在表单中包装添加注释功能,然后通过相应的操作将其发布回服务器即可。 That action can return the entire view with the new comment added if you would like. 如果需要,该操作可以返回整个视图,并添加新的注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM