简体   繁体   中英

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

[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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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