我知道它并没有真正回答你的问题,只是为了扩展我的评论:-
听起来你有类似的东西:-
public class MyModel
{
[Required]
public string Foo { get; set; } // Populated in step 1
[Required]
public string Bar { get; set; } // Populated in step 2
}
您在发布第 1 步时遇到问题,因为用户尚未输入 Bar 的值,所以有一个 ModelStateError。
我更喜欢的解决方案是在每个向导步骤中使用 ViewModel 将您的视图实现与模型实现分离,而不是试图搞乱您的持久性模型的验证,例如:-
public class MyModel
{
[Required]
public string Foo { get; set; }
[Required]
public string Bar { get; set; }
}
public class StepOneModel
{
[Required]
public string Foo { get; set; }
}
public class StepTwoModel
{
// This really depends on the behaviour you want.
// In this example, the model isn't persisted until
// the last step, but you could equally well persist
// the partial model server-side and just include a
// key in subsequent wizard steps.
[Required]
public StepOneModel StepOne { get; set; }
[Required]
public string Bar { get; set; }
}
您的控制器操作类似于:-
public ActionResult StepOne()
{
return View(new StepOneViewModel());
}
[HttpPost]
public ActionResult StepOne(StepOneViewModel model)
{
if(ModelState.IsValid)
{
var stepTwoModel = new StepTwoViewModel ()
{
StepOne = model
};
// Again, there's a bunch of different ways
// you can handle flow between steps, just
// doing it simply here to give an example
return View("StepTwo", model);
}
return View(model);
}
[HttpPost]
public ActionResult StepTwo(StepTwoViewModel model)
{
if (ModelState.IsValid)
{
// You could also add a method to the final ViewModel
// to do this mapping, or use something like AutoMapper
MyModel model = new MyModel()
{
Foo = model.StepOne.Foo
Bar = model.Bar
};
this.Context.MyModels.Add(model);
this.Context.SaveChanges();
}
return View(model);
}
您的 StepOne 视图类似于:-
@model StepOneModel
@using (html.BeginForm()) {
@html.EditorFor(x => x.Foo);
}
您的 StepTwo 视图类似于:-
@model StepTwoModel
@using (html.BeginForm("StepTwo")) {
@html.HiddenFor(x => x.StepOne);
@html.EditorFor(x => x.Bar);
}
与仅关闭模型验证相比,主要优势在于您可以将当前步骤的验证要求放在 ViewModel 上 - 您可以确保第一步中的所有值都有效,然后再进行第二步。