通过邮寄表格传递外键

时间:2016-09-22 22:27:39

标签: asp.net-mvc

我正在创建一个帮助台系统。我首先使用代码,所以我创建了一些我将简要描述的脚本。

这门课是我的主要课程

public class Ticket
{
    public int Id { get; set; }
    [Required]
    [StringLength(255)]
    public string Name { get; set; }
    [Required]
    [Display(Name = "Descrição")]
    public string Description { get; set; }
    public TicketStatus TicketStatus { get; set; }
    public byte TicketStatusId { get; set; }
}

我创建了这个类,用fk来处理票证

public class TicketAnswer
{
    public int Id { get; set; }
    public Ticket Ticket { get; set; }
    public int TicketId { get; set; }
    public string Message { get; set; }
}

要创建我的表单,我创建了一个viewmodel来处理所有票证答案

public class AnswerTicketViewModel
{
    //public IEnumerable<TicketStatus> TicketStatus { get; set; }
    public Ticket Ticket { get; set; }
    public List<TicketAnswer> TicketAnswer { get; set; }
    public string Message { get; set; }
}

并传递此表单

@using (Html.BeginForm("SaveAnswer", "Ticket"))
{
    @Html.AntiForgeryToken()

    @Html.HiddenFor(model => model.Ticket.Id)
    <div class="form-group">
        @Html.LabelFor(model => model.Message, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextAreaFor(model => model.Message, 10, 50, new { htmlAttributes = new { @readonly = "readonly", disabled = "disabled", @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Message, "", new { @class = "text-danger" })
        </div>
    </div>

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

}

这是行动

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult SaveAnswer(TicketAnswer ticket)
    {
        if (!ModelState.IsValid)
        {
            var ticketStatus = _context.TicketStatus.ToList();
            var ticketAnswer = _context.TicketAnswer.Where(t => t.TicketId == ticket.Ticket.Id).ToList();

            var viewModel = new AnswerTicketViewModel
            {
                Ticket = ticket.Ticket,
                TicketAnswer = ticketAnswer
            };
            return View("AnswerTicketForm", viewModel);
        }

        _context.TicketAnswer.Add(ticket);
        _context.SaveChanges();

        return RedirectToAction("Index", "Ticket");
    }

我收到错误“INSERT语句与FOREIGN KEY约束冲突”FK_dbo_TicketAnswers_dbo_Tickets_TicketId“我如何更改并处理此fk?我尝试各种解决方案可以有人给出提示吗?

1 个答案:

答案 0 :(得分:0)

我的viewmodel上有人把我在表单上设置的变量放到了票证的id上并且它仍然存在于post方法

public class AnswerTicketViewModel
{
    //public IEnumerable<TicketStatus> TicketStatus { get; set; }
    public Ticket Ticket { get; set; }
    public int TicketId { get; set; }
    public List<TicketAnswer> OtherAnswers { get; set; }
    public TicketAnswer TicketAnswer { get; set; }
}

@Html.HiddenFor(model => model.TicketId, new { Value=Model.Ticket.Id })

所以我能用这个外键处理数据库,谢谢你们