簡體   English   中英

創建子對象時如何從子對象內的父對象獲取ID? (MVC)

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

概觀

我正在將ASP.NET Core與MVC結合使用。

我正在嘗試制作一個簡單的幫助台系統作為實驗。

它有2個對象,一個查詢和一個注釋

  • 查詢包含評論列表。

  • 注釋具有其所屬查詢的ID。

我的問題是

如何獲取要添加到評論屬性中的查詢ID(是正在創建的評論的父級)?


代碼示例

CommentsController.Create

我嘗試了2個POST示例,似乎都從注釋中捕獲了表單數據,但是我不知道如何在該表單數據中引入查詢ID。 當我創建孩子評論時。 查詢ID已添加到我發送到“創建”視圖的模型中,但在該視圖中提交表單時丟失了。 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)

查看/評論/ 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>


詳細說明MVC程序中的當前流程,以更好地理解

要將注釋添加到查詢中,我進行了以下設置。

  1. 查詢詳細信息視圖上的按鈕觸發名為“ CreateComment”的InquiryController上的操作。 這將重定向到帶有查詢ID的Comments控制器。
  2. CommentsController收到了重定向以及附加的InquiryID。 然后,它發送回Create視圖以創建注釋,在該視圖中以模型形式發送CommentCreation對象。 這保留了父咨詢的ID以及新的/空的注釋。
  3. 在評論創建視圖中,輸入評論信息並提交。
  4. 提交的表單信息現在已被Create“捕獲”,我可以看到評論的信息。 但是, 這就是問題所在 ,父Inquiry的ID在該過程中丟失了,現在設置為默認值0(因為它是整數)。

楷模

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

您需要在<form>包含路由/查詢字符串值,或者為IDOfInquiryBelongingTo包含隱藏的輸入,以便其值在請求中發送並綁定到您的模型。

但是,在編輯數據(您的Comment屬性)時,視圖模型不應包含數據模型,並且TimePosted似乎是用戶不可編輯的屬性。 我建議您首先將視圖模型修改為

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

您的GET方法現在將向視圖返回CommentVM的實例

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

視圖

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

然后在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM