ASP.Net 核心异常 - 无法为模型对象创建模型绑定器

ASP.Net Core Exception - Could not create a model binder for model object

我还是 MVC 的新手,我正在努力解决默认绑定在表单提交到期望视图模型的控制器时失败的问题。我曾尝试将模型绑定属性 [FromForm] 添加到构造函数但没有成功,我已经开始阅读有关自定义绑定器的信息,但在这种情况下感觉有点过分了。如果我需要 post 全部 HTML 我可以做到。

我真的很感激在这方面的一些指导,非常感谢所有帮助?我什至都在努力调试和命中断点。

InvalidOperationException: Could not create a model binder for model object >of type 'XX.Models.ClientEditViewModel'.

型号

public partial class ClientEditViewModel
{
  public ClientEditViewModel(List<ProgramViewModel> programs)
  {
    this.Programs = programs;
  }
  public int ClientId { get; set; }
  public string ClientName { get; set; }
  public List<ProgramViewModel> Programs { get; set; }
}

表格

@model XX.Models.ClientEditViewModel
<form asp-action="EditClient" method="post">
      <div class="form-horizontal">
        <input type="hidden" asp-for="@Model.ClientId" />
        <div class="form-group">
            <label asp-for="@Model.ClientName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="@Model.ClientName" class="form-control" />
                <span asp-validation-for="@Model.ClientName" class="text-danger" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Update" class="btn btn-default" />
            </div>
        </div>
    </div>
</form>

控制器

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditClient(ClientEditViewModel clientedit)
{
if (ModelState.IsValid)
{
    Client client = await dbcontext.Client.SingleOrDefaultAsync(m => m.Id == clientedit.ClientId);
    try
    {
        client.Name = clientedit.ClientName;
        dbcontext.Client.Update(client);
        await dbcontext.SaveChangesAsync();
    }
    catch (Exception ex)
    {
        string error = ex.InnerException.ToString();
        if (!ClientExists(clientedit.ClientId))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    TempData["msg"] = "You have successfully edited " + clientedit.ClientName + ".";
    return RedirectToAction("Index");
}

return null;
}

默认绑定使用无参数构造函数,而您的模型具有需要自定义绑定的自定义构造函数。这里有一个类似的postPosting data when my view model has a constructor does not work

在你的例子中,Programs 有一个 setter,所以我会完全删除自定义构造函数。