【发布时间】:2016-02-06 13:20:40
【问题描述】:
在我的 MVC Web 应用程序中,我有两个 Html.BeginForm(),它们具有相同的控制器和对单个视图的不同操作。当我单击第一个Html.BeginForm() 的按钮时,它会显示两个表单的验证消息,而我只希望它用于单个表单。看看我下面的代码。
//First Html.BeginForm()
@using (Html.BeginForm("AddFirst", "Student", FormMethod.Post, new { id = "form1", role = "form" }))
{
<tr>
<td>
@Html.LabelFor(model => model.MobileNo)
@Html.EditorFor(model => model.MobileNo, new { htmlAttributes = new { id = "TextMobile", @class = "form-control", @maxlength = "10", @placeholder = "Mobile No" } })
@Html.ValidationMessageFor(model => model.MobileNo, "", new { @class = "text-danger" })
</td>
<td>
<input type="submit" name="submit" value="First Button" class="btn btn-default" />
</td>
</tr>
}
//Second Html.BeginForm()
@using (Html.BeginForm("AddSecond", "Student", FormMethod.Post, new { id = "form2", role = "form" }))
{
<tr>
<td>
@Html.LabelFor(model => model.MobileNo)
@Html.EditorFor(model => model.MobileNo, new { htmlAttributes = new { id = "TextMobile2", @class = "form-control", @maxlength = "10", @placeholder = "Mobile No" } })
@Html.ValidationMessageFor(model => model.MobileNo, "", new { @class = "text-danger" })
</td>
<td>
<input type="submit" name="submit" value="Second Button" class="btn btn-default" />
</td>
</tr>
}
在上述情况下,当我单击第一个按钮时,它显示两个手机号码的验证消息,但我想显示一个手机号码的验证消息(第二个按钮相同)。如何仅验证特定形式的单个文本框?为此,我采取了不同的行动。在我的控制器中,我有两个动作。
[HttpPost]
public ActionResult AddFirst(string submit, User u)
{
agree = new Agree(u);
if (ModelState.IsValid)
{
//Some logic
return View("ThisView", agree);
}
else
{
return View("ThisView", agree);
}
}
[HttpPost]
public ActionResult AddSecond(string submit, User u)
{
agree = new Agree(u);
if (ModelState.IsValid)
{
//Some logic
return View("ThisView", agree);
}
else
{
return View("ThisView", agree);
}
}
在我的模型中,我有
[DisplayName("Mobile Number")]
[Required(ErrorMessage = "* Please Enter Mobile Number")]
public string MobileNo { get; set; }
【问题讨论】:
-
您的代码对我有用...再检查一次...
-
它可以工作,但是当我单击任何形式的单个按钮时,它会显示两个文本框的验证,我只希望显示特定文本框的一个验证。我怎样才能做到这一点?
-
因为您要为相同的属性创建多个
ValidationMessageFor()。这有什么意义 - 你一次只能提交一个表单 - 你的实现没有意义
标签: c# asp.net-mvc validation asp.net-mvc-5