![](/img/trans.png)
[英]asp.net mvc how can I pass the view model and input text to controller?
[英]How can I manually validate a model in the controller after altering the request using ASP.NET MVC 5?
在ASP.NET MVC 5框架的顶部编写了一个应用程序。
我的页面有两种不同的形式(加载页面时一种可见,另一种隐藏)。 第一种形式有一个下拉菜单,如果用户选择选项“ ABC”,我将使用javascript来显示第二种形式。 但是,如果他/她选择了其他任何选项,我将隐藏第二种形式。
使用javascript,由于表单不可见,因此我将必填字段的必填属性更改为可选。 (仅对客户端执行此操作)
现在,由于第二个表单在服务器端具有一些必填字段,因此每次我提交表单时,属性ModelState.IsValid
始终为false,因为第二个表单具有一些未提供的必填字段。
不知何故,在验证表单之前,我需要通过将SecondForm
属性设置为null然后进行验证来更改模型。
这是我的ViewModelCapsule
类的样子
public class ViewModelCapsule
{
public FirstFormViewModel FirstForm { get; set; }
public SecondFormViewModel SecondForm { get; set; }
}
我试图通过在控制器上使用TryValidateModel()
方法来解决此问题,如下所示
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Update(int id, ViewModelCapsule model)
{
try
{
if(model.FirstModel != null && model.FirstModel.Menu1 != "ABC")
{
model.SecondModel = null
}
if (TryValidateModel(model))
{
// Here I am expecting the form to validate since the first form has valid date
// Do somethig with the request
}
return new RedirectAction("Index");
}
catch (Exception exception)
{
return Content(exception.Message);
}
}
但由于某些原因, TryValidateModel(model)
也返回false。 我评估了传入的数据,并且FirstForm
在其所有属性中都有正确的数据。
更改请求后,如何在控制器中手动验证模型?
我相信我现在就可以使用它。 我必须将这行代码添加到我的控制器中
ModelState.Clear();
我的控制器看起来像这样
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Update(int id, ViewModelCapsule model)
{
try
{
if(model.FirstModel != null && model.FirstModel.Menu1 != "ABC")
{
ModelState.Clear();
model.SecondModel = null
}
if (TryValidateModel(model))
{
// Here I am expecting the form to validate since the first form has valid date
// Do somethig with the request
}
return new RedirectAction("Index");
}
catch (Exception exception)
{
return Content(exception.Message);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.