【发布时间】:2015-06-01 17:46:52
【问题描述】:
之后编辑:
我应该更好地表达我最初的问题:在下面的示例中,我使用了两种形式:
using (Html.BeginForm....
在控制器中,我将如何只验证一种形式,而不是整个模型?这甚至可能吗?或者,我是否试图以不符合预期的方式使用 MVC?多年来,我一直是 ASP.NET 表单专家。还在学习 MVC。
//结束编辑
我有一个表单视图,需要以两部分(或两页)表单的形式呈现。这两部分都有一些必填字段。我可以模拟多页表单,但我遇到的问题是验证。对于每篇文章,它都会验证整个视图上的所有字段。如何让它仅验证当前可见的字段?
这是我现在拥有的(简化的):
型号:
public Boolean Page1Complete { get; set; }
public Boolean Page2Complete { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.CustomerSatisfactionSurvey), ErrorMessageResourceName = "Page1Question1Required")]
public int? LikelyToReturn { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.CustomerSatisfactionSurvey), ErrorMessageResourceName = "Page2Question1Required")]
public int? RecomendToFriend { get; set; }
查看:
if (!Model.Page1Complete)
{
using (Html.BeginForm("PatientSatisfactionSurveyPage1", "Forms", FormMethod.Post, new { id = "patient-satisfaction-survey-page-1", @class = "full-form" }))
{
@for (var a = 0; a < 11; a++)
{
@a - @Html.RadioButtonFor(model => Model.LikelyToReturn, @a)
}
<input type="submit" id="page1-submit" name="page1-submit" value="Continue" class="btn green2">
}
}
else
// Page1 was submitted successfully. Display Page 2
{
using (Html.BeginForm("PatientSatisfactionSurveyPage2", "Forms", FormMethod.Post, new { id = "patient-satisfaction-survey-page-2", @class = "full-form" }))
{
@for (var a = 0; a < 11; a++)
{
@a - @Html.RadioButtonFor(model => Model.RecomendToFriend, @a)
}
<input type="submit" id="page2-submit" name="page2-submit" value="Complete" class="btn green2">
}
}
控制器:
[HttpPost]
public ActionResult PatientSatisfactionSurvey([Bind]PatientSatisfactionSurveyPage pss)
{
//Process and validate the first page
if (Request.Form["page1-submit"] != null)
{
if (ModelState.IsValid)
{
pss.Page1Complete = true;
// Page 1 Logic...
}
}
//Process and validate the first page
if (Request.Form["page2-submit"] != null)
{
if (ModelState.IsValid)
{
pss.Page2Complete = true;
// Page 2 Logic...
}
}
}
【问题讨论】:
-
为什么一定要用同样的动作方法?
-
卢卡斯,我不知道。我是 MVC 的新手。多年来一直在做标准的 ASP.NET 表单。无法理解 MVC 是如何工作的。你能告诉我如何使用单独的操作方法,以及这将如何帮助解决我的问题吗?谢谢!
-
还有什么我可以添加到我的答案中以使其成为最佳答案吗? (检查按钮)
-
卢卡斯,在你的回答下方查看我的问题。
-
您始终可以使用单个表单并根据this answer验证单个控件或控件组
标签: c# asp.net-mvc forms validation razor