C# 如何在ASP.NETMVC中验证特定模型实例的特定字段/属性?
我有一个具有4个属性的模型类:C# 如何在ASP.NETMVC中验证特定模型实例的特定字段/属性?,c#,asp.net,asp.net-mvc,model,C#,Asp.net,Asp.net Mvc,Model,我有一个具有4个属性的模型类: public class ModelClass { [Required] public string Prop1 { get; set; } [MaxLength(5)] public string Prop2 { get; set; } [MinLength(5)] public string Prop3 { get; set; } [M
public class ModelClass
{
[Required]
public string Prop1 { get; set; }
[MaxLength(5)]
public string Prop2 { get; set; }
[MinLength(5)]
public string Prop3 { get; set; }
[MinLength(5)]
public string Prop4 { get; set; }
}
视图,其中我仅输入prop2:
@model ModelClass
@Html.TextBoxFor(m => m.Prop2)
和一些控制器:
[HttpPost]
public ActionResult Index(ModelClass postedModel)
{
var originalModel = Session["model"] as ModelClass;
return View();
}
问题是:整个模型存储在会话中,因为它是在单独的视图中填充的。我需要的是只验证模型的Prop1
,它存储在会话中。如果验证失败,我需要重定向到其他一些view 1
,如果Prop1
被调用或view 3
如果Prop3
无效等。在控制器中,我只发布了Prop2
模型和会话中的模型。我不能使用ModelState
及其方法,例如ModelState.IsValidField()
,因为它将是发布模型的验证信息。另外,我不能使用controller.TryValidateModel(originalModel)
,因为我只得到false
,我不会得到关于为什么它是false
,所以如果Prop1
无效,我将无法重定向到View1
,或者如果Prop3
无效,我将无法重定向到View3
那么如何仅验证原始模型的Prop1?使用视图模型:
public class Step1ViewModel
{
[Required]
public string Prop1 { get; set; }
}
然后将视图强类型化为视图模型:
@model Step1ViewModel
@Html.TextBoxFor(m => m.Prop1)
最后,让您的HttpPost控制器操作将视图模型作为操作参数,以便您只能在当前向导步骤的上下文中成功验证它:
[HttpPost]
public ActionResult Index(Step1ViewModel postedModel)
{
if (!ModelState.IsValid)
{
// validation for this step failed => redisplay the view so that the
// user can fix his errors
return View(postedModel);
}
// validation passed => fetch the model from the session and update the corresponding
// property
var originalModel = Session["model"] as ModelClass;
originalModel.Prop1 = postedModel.Prop1;
return RedirectToAction("Step2");
}