简体   繁体   English

创建子对象时如何从子对象内的父对象获取ID? (MVC)

[英]How to get ID from parent object inside child object when creating it? (MVC)

Overview 概观

I'm using ASP.NET Core with MVC. 我正在将ASP.NET Core与MVC结合使用。

I am trying to make a simple helpdesk system as an experiment. 我正在尝试制作一个简单的帮助台系统作为实验。

It has 2 objects, an Inquiry and a Comment . 它有2个对象,一个查询和一个注释

  • An Inquiry has a list of comments. 查询包含评论列表。

  • A comment has the ID of the Inquiry it belongs to. 注释具有其所属查询的ID。

My question is 我的问题是

How can I get the ID of the Inquiry (which is a parent of the comment being created) to be added to a property in the comment? 如何获取要添加到评论属性中的查询ID(是正在创建的评论的父级)?


Code examples 代码示例

CommentsController.Create CommentsController.Create

I have tried the 2 POST examples, both seem to capture the form data from the comment but I don't know how to also bring in the Inquiry ID in that form data. 我尝试了2个POST示例,似乎都从注释中捕获了表单数据,但是我不知道如何在该表单数据中引入查询ID。 When I am creating a child comment. 当我创建孩子评论时。 The Inquiry ID was added to the model I sent to the Create view but lost when submitting the form in that view. 查询ID已添加到我发送到“创建”视图的模型中,但在该视图中提交表单时丢失了。 The GET example works as intended. GET示例按预期工作。

    // GET: Comments/Create
    public IActionResult Create([FromRoute] int id) //id = InquiryID

    // POST: Comments/Create
    public async Task<IActionResult> Create(CommentCreationDTO commentCreationDTO)

    public async Task<IActionResult> Create([FromForm]CommentCreationDTO commentCreationDTO)

Views/Comments/Create.cshtml 查看/评论/ Create.cshtml

@model HelpDesk2018.Models.CommentCreationDTO
@{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<h4>Comment</h4>
<hr/>
<div class="row">
<div class="col-md-4">
    <form asp-controller="Comments" asp-action="Create" method="post">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="@Model.Comment.TimePosted" class="control-label"></label>
            <input asp-for="@Model.Comment.TimePosted" class="form-control" />
            <span asp-validation-for="@Model.Comment.TimePosted" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="@Model.Comment.Text" class="control-label"></label>
            <input asp-for="@Model.Comment.Text" class="form-control" />
            <span asp-validation-for="@Model.Comment.Text" class="text-danger"></span>
        </div>
    </form>
</div>


Elaboration of the current flow in the MVC program for better understanding 详细说明MVC程序中的当前流程,以更好地理解

To add comments to the Inquiry I have made the following setup. 要将注释添加到查询中,我进行了以下设置。

  1. A button on the Inquiry detail view triggers an action on the InquiryController named "CreateComment". 查询详细信息视图上的按钮触发名为“ CreateComment”的InquiryController上的操作。 This redirects to the Comments controller with the ID of the inquiry. 这将重定向到带有查询ID的Comments控制器。
  2. The CommentsController received the redirect plus the attached InquiryID. CommentsController收到了重定向以及附加的InquiryID。 It then sends back the Create view for creating comments, in the view a CommentCreation object is sent in as model. 然后,它发送回Create视图以创建注释,在该视图中以模型形式发送CommentCreation对象。 This holds the ID of the parent Inquiry as well as a new/empty comment. 这保留了父咨询的ID以及新的/空的注释。
  3. On the comment creation view I enter the comment information and submit. 在评论创建视图中,输入评论信息并提交。
  4. The form info submitted is now "caught" by the Create and I can see the information of the comment. 提交的表单信息现在已被Create“捕获”,我可以看到评论的信息。 However, and this is the issue , the ID for the parent Inquiry was lost in the process and now is set to the default value of 0 (as it's an integer). 但是, 这就是问题所在 ,父Inquiry的ID在该过程中丢失了,现在设置为默认值0(因为它是整数)。

Models 楷模

/// <summary>
/// Represents one inquiry on the helpdesk.
/// Category, Country and RelatedProduct should perhaps be objects instead of strings.
/// </summary>
public class Inquiry : TextPost
{
    public string Title { get; set; }
    public bool Solved { get; set; }
    public bool Private { get; set; }
    public List<Comment> Comments { get; set; } = new List<Comment>();
    public string Category { get; set; }

    #region optional properties
    /// <summary>
    /// Which country this inquiry is most relevant for. E.g. Denmark, Sweden, Norway etc., but can also be "All" or the name of a specific market.
    /// </summary>
    public string Country { get; set; }
    /// <summary>
    /// In case the inquiry is related to one or more products. Should perhaps be an object in it's own right instead of a string as it is now.
    /// </summary>
    public string RelatedProduct { get; set; }
    #endregion
}

public class Comment : TextPost
{
    public int InquiryID { get; set; }
}

public class TextPost
{
    [Key]
    public int ID { get; set; }
    public User User { get; set; }
    public DateTime TimePosted { get; set; }
    /// <summary>
    /// The main text.
    /// </summary>
    public string Text { get; set; }
}

public class CommentCreationDTO
{
    public int IDOfInquiryBelongingTo { get; set; }
    /// <summary>
    /// The comment that is being created.
    /// </summary>
    public Comment Comment { get; set; }
}

You need to include a route/query string value in the <form> or include a hidden input for IDOfInquiryBelongingTo , so that its value is sent in the request and will be bound to your model. 您需要在<form>包含路由/查询字符串值,或者为IDOfInquiryBelongingTo包含隐藏的输入,以便其值在请求中发送并绑定到您的模型。

However, view models should not contain data models when editing data (your Comment property), and TimePosted appears to be a property that should not be editable by the user. 但是,在编辑数据(您的Comment属性)时,视图模型不应包含数据模型,并且TimePosted似乎是用户不可编辑的属性。 I recommend you first modify the view model to 我建议您首先将视图模型修改为

public class CommentVM
{
    public int? ID { get; set; } // if you also want to use this for editing existing comments
    [Required]
    public int? InquiryID { get; set; }
    [Required(ErrorMessage = "Please enter a comment")]
    public string Text { get; set; }
}

Your GET method will now return an instance of CommentVM to the view 您的GET方法现在将向视图返回CommentVM的实例

public IActionResult Create([FromRoute] int id) //id = InquiryID
{
    CommentVM model = new CommentVM
    {
        InquiryID = id
    }
    return View(model);
}

View 视图

@model ....CommentVM
<form asp-controller="Comments" asp-action="Create">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <input type="hidden" asp-for="InquiryID" /> // add hidden input
    <div class="form-group">
        <label asp-for="Text" class="control-label"></label>
        <input asp-for="Text" class="form-control" />
        <span asp-validation-for="Text" class="text-danger"></span>
    </div>
</form>

And in the POST method, map the view model to the data model 然后在POST方法中,将视图模型映射到数据模型

public async Task<IActionResult> Create([FromForm]CommentVM model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    Comment comment = new Comment
    {
        InquiryID = model.InquiryID,
        Text = model.Text,
        TimePosted = DateTime.Now,
        .... // set other properties (User etc) as required
    };
    // save and redirect
    ....
}

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

相关问题 如何在Agile Central API中获取孩子的祖父母对象ID - How to get grand parent Object ID for a child in Agile Central API 在NHibernate中通过ID或父对象获取子对象? - Get child objects by id or parent object in NHibernate? 从NHibernate中的子级联创建时,如何获得新的父级ID? - How do I get a new parent ID when cascade creating from a child in NHibernate? 如何从子对象获取/更新父对象的属性 - How to get/update property of parent object from child object 创建父对象时,Entity Framework正在创建新的子对象 - Entity Framework is creating new child object when parent object is created 流利的具有自动映射功能的nHibernate:如何从子级获取父级或“污染”对象 - Fluent nHibernate with Automapping: How to get a parent or “containg” object from a child 父级销毁时如何销毁子级对象? - How to destroy child object when parent is destroyed? 在父对象内映射子对象 - Mapping child object inside parent object 当我不控制子对象时,从子对象中识别出父对象 - Identifying a parent object from a child object, when I don't control the child object 为什么当我尝试从父类(向下转换)创建子 class 时,我得到 null object - why is it when I try to create a child class from a parent class(Downcasting), I get a null object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM