【问题标题】:how use two modeles in one method?如何在一种方法中使用两个模型?
【发布时间】:2020-05-17 11:39:27
【问题描述】:

ModelState 无效。我认为我错误地传递了模型。有什么想法吗?

控制器:

    [Authorize]
    [HttpPost]
    public async Task<IActionResult> SendComment([Bind("CommentID,Comment,Date,AdminId")]AdminReport adminReport,int ReportID)
    {
        var x = _userReport.UserReports.Find(ReportID);
        x.IsViewed = true;
        adminReport.UserId = x.UserId;
        adminReport.AdminId = _userManager.GetUserId(HttpContext.User);
        if (ModelState.IsValid){
            _adminReport.Add(adminReport);
            await _adminReport.SaveChangesAsync();
            return View(); }

        return RedirectToAction("SendDoneAdmin");
    }

这是我传递模型的方式:

 <div class="card-footer">
    <form asp-controller="Admin" asp-action="ُSendComment" method="post">
        <input type="hidden" value="@report.ReportID" name="ReportID" />
        <button type="submit" class="btn btn-primary">SendComment</button>
    </form>

型号: [钥匙] 公共 int CommentID { 获取;放; }

    [Required]
    public string Comment { get; set; }


    public string AdminId { get; set; }

    public string UserId { get; set; }
}`

【问题讨论】:

    标签: asp.net-core model-view-controller asp.net-core-mvc


    【解决方案1】:

    您的报价不清楚,但必须知道通过 Form 标签传递数据 必须在 Form 标签内全部输入

    控制器

    public async Task<IActionResult> SendComment()
    {
        // write your code....
        return View(new AdminReport()); // must return new object
    }
    

    发布

    正常写下你的动作SendComment没有任何变化

    HTML

    为了通过AdminReport模型必须在form标签里面写飞

    <form asp-controller="Admin" asp-action="Viewed" method="post">
        <input type="hidden" value="@report.ReportID" name="ReportID" />
        /* for example */
        <input type="hidden"  asp-for="model.Comment" /> 
        <button type="submit" class="btn btn-primary">SendComment</button>
    </form>
    

    如果您有另一个视图但必须返回 View(new AdminReport()); 没有问题

    如果您想删除评论道具的验证,请使用下面的代码。

     // remove all key
        foreach (var key in ModelState.Keys).ToList())
                    ModelState.Remove(key);
      // or for one
      ModelState.Remove("comment ");
    

    【讨论】:

    • 实际上我对我的“SendComment”方法有另一个视图。但它没有显示,因为 ModelState 无效。
    【解决方案2】:

    你把这个[Requiried]属性放在Comment上:

        [Required]
        public string Comment { get; set; }
    

    您必须在表单中包含该输入才能通过验证。 您可以像这样添加该字段:

     <div class="card-footer">
        <form asp-controller="Admin" asp-action="Viewed" method="post">
            <input type="hidden" value="@report.ReportID" name="ReportID" />
            <input type="text" name="Comment" />
            <button type="submit" class="btn btn-primary">SendComment</button>
        </form>
    

    【讨论】:

      猜你喜欢
      • 2015-07-11
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多