我有一个控制器设置为 1 的模型属性,但在我看来,我将其视为 0 和 1,具体取决于我如何访问它。
查看片段(这些行也是绝对连续的!)
@Html.DisplayFor(model => model.resumeStage)
@Html.HiddenFor(model => model.resumeStage)
@Html.EditorFor(model => model.resumeStage)
渲染的 HTML(value=
为了便于阅读,我移动了标签前面的 )
1
<input value="0" data-val="true" data-val-number="The field resumeStage must be a number." data-val-required="The resumeStage field is required." id="resumeStage" name="resumeStage" type="hidden" />
<input value="0" class="text-box single-line" id="resumeStage" name="resumeStage" type="number" />
值不应该总是1吗?当我在文本框中显示该属性时,我似乎失去了它的状态!视图控制器受模型类的严格约束,模型类定义为
public class CreateUserModel
{
[Required]
public int resumeStage { get; set; } // <== problem
public LocalProfile newLocalUser { get; set; }
public ExtProfile newExtUser { get; set; }
public CreateUserModel()
{
resumeStage = 0;
newLocalUser = new LocalProfile();
newExtUser = new ExtProfile();
preFillWithTestData();
}
private void preFillWithTestData()
{
// prefill the newLocalUser
// and newExtUser classes with dummy data
}
}
接收表单 POST 的控制器方法(我将 int 从 0 => 1 翻转)是:
[HttpPost]
public ActionResult UserRegistration(CreateUserModel newUser)
{
try
{
//stage 0, setup local account
if (newUser.resumeStage <= 0)
{
// do stuff
newUser.resumeStage = 1;
}
// stage 1, setup external account
if (newUser.resumeStage <= 1)
{
// test an exception
Exception ex = new Exception("TEST: External service provider offline");
throw ex;
newUser.resumeStage = 2;
}
return RedirectToAction("Index");
}
catch (Exception ex)
{
return View(newUser); // newUser.resumeStage is 1 here but
// view will disagree
}
}
创建和呈现表单的控制器方法是:
public ActionResult UserRegistration()
{
// Constructor prefills with test data, nothing more to do
CreateUserModel newUser = new CreateUserModel();
return View(newUser);
}
问题:有谁知道为什么我似乎无法在 HTML 呈现的文本框中将 resumeStage 显示为 1?