【发布时间】:2022-01-14 18:35:15
【问题描述】:
我在从控制器加载 ViewComponent 时遇到问题,我的主视图是 Contact.cshtml,而我的 ViewComponent 是 AddContact.cshtml。 AddContact 是一个带有提交按钮的简单表单,我正在尝试获取它,以便当模型无效时,组件会刷新输入的数据和模型验证消息。
问题是当我在控制器中返回 "ViewComponent("AddContact", newContact)" 时,模型“newContact”无效,它会在一个全新的页面中重新加载 ViewComponent,而不是作为联系人视图中的一部分。是否有一些我遗漏的语法或者这完全需要其他东西?
联系方式.cshtml:
@await Component.InvokeAsync("AddContact", new { addContact = newContactModel })
AddContact.cshtml
@using (Html.BeginForm("AddContact", "Contact", FormMethod.Post))
{
....
<input id="addContactBtn" type="submit" value="Add" class="btn btn-success">
}
控制器:
[HttpGet]
public ActionResult AddContact()
{
return ViewComponent("AddContact");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddContact(AddContact_VM newContact)
{
if (!ModelState.IsValid)
{
return ViewComponent("AddContact", newContact);
}
OperationStatus opStat = granteeRepo.AddContact(newContact);
return View("Contact");
}
组件:
public class AddContact : ViewComponent
{
public IViewComponentResult Invoke(AddContact_VM newContact)
{
return View("AddContact", newContact);
}
}
【问题讨论】:
标签: c# asp.net-mvc asp.net-core model-validation asp.net-core-viewcomponent