0

我有一个具有 4 个属性的模型类:

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();
        }

问题是:整个模型都存储在 中Session,因为它填充在单独的视图中。我需要的是仅验证Prop1模型,该模型存储在Session. 如果验证失败,我需要重定向到其他一些View1if Prop1is invlaid 或View3if Prop3is invalid 等。在控制器中,我只发布了模型Prop2和来自Session. 我不能使用ModelState它的方法ModelState.IsValidField(),例如,因为它将是发布模型的验证信息。我也不能使用controller.TryValidateModel(originalModel),因为我只是得到false并且我不会得到关于它为什么是的信息false,所以我将无法重定向到View1if Prop1is invalid 或 to View3if Prop3is invalid。那么我怎样才能只验证 originalModel 的 Prop1 呢?

4

1 回答 1

1

Use view models:

public class Step1ViewModel
{
    [Required]
    public string Prop1 { get; set; }
}

and then make your view strongly typed to the view model:

@model Step1ViewModel
@Html.TextBoxFor(m => m.Prop1) 

and finally have your HttpPost controller action take the view model as action argument so that you could successfully validate it only in the context of the current wizard step:

[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");
}
于 2013-01-13T12:51:31.423 回答