Html.beginform验证服务器端和客户端端
问题描述:
处理我的第一个ASP.NET MVC应用程序,并有一些表单验证问题。Html.beginform验证服务器端和客户端端
我有我的模型:
public class InfoFormEmplModel
{
public int supID { get; set; }
public string description { get; set; }
public InfoFormEmplModel() {}
}
注意,这种模式并不代表在我DATABSE任何表。现在
,在我看来:
@using Portal.Models
@model InfoFormEmplModel
@{
ViewBag.Title = "Form";
}
@using (Html.BeginForm())
{
<b>Sup</b> @Html.TextBoxFor(x => x.supID)
<p>Description</p>
@Html.TextAreaFor(x => x.description)<br><br>
<input type="submit" name="Save" value="Soumettre" />
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
我需要做一些验证,该字段必须不能是空的,我也有检查supId提供存在于我的数据库(服务器端验证)
我想一些验证添加到我的模型:
public class InfoFormEmplModel
{
[Required (ErrorMessage = "Superior ID required")]
public int supID { get; set; }
[Required (ErrorMessage = "Description required")]
public string description { get; set; }
public InfoFormEmplModel() {}
}
,并还增加了@ Html.ValidationMessageFor我的看法:
@using Portal.Models
@model InfoFormEmplModel
@{
ViewBag.Title = "Form";
}
@using (Html.BeginForm())
{
<b>Sup</b> @Html.TextBoxFor(x => x.supID)
@Html.ValidationMessageFor(x => x.supID)
<p>Description</p>
@Html.TextAreaFor(x => x.description)<br><br>
@Html.ValidationMessageFor(x => x.description)
<input type="submit" name="Save" value="Soumettre" />
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
我的控制器看起来是这样的:
[HttpPost]
public PartialViewResult invform(InfoFormEmplModel form)
{
//check if supID exists
bool exists = librairie.supExists(form.supID);
if (!exists)
{
return PartialView("ErreurDuplicat");
}
return PartialView("Success");
}
当我离开supID空,验证似乎没有occur..My控制器就向我的模型到检查Superieur的标识是另一个类在数据库中但supID没有任何价值。我期待,在控制器进行之前,我会看到网页上的错误消息..
此外,一旦我检查如果supID存在数据库中,我如何显示错误消息在我的看法,所以用户可以输入一个有效的supID?
答
假设您始终使用相同的视图模型(并且为了清晰起见您进行了翻译和缩短),您应该在后期操作中获取视图模型。然后,您可以使用ModelState属性根据您的验证注释检查接收到的模型是否有效。
如果你的模型是有效的,你的SupId做服务器端检查,如果你想,如果这样的ID已经存在,你可以做到这一点,如下面的代码片段设置了一个错误:
[HttpPost]
public ActionResult invform(InfoFormEmplModel form)
{
if (ModelState.IsValid)
{
//set an error when the id exists
ModelState.AddModelError("supId", "The Id is already in use. Please chose a different Id");
return View(form);
}
return View(form);
}
对于其他错误是不可能的,你收到一个空id,因为它是一个int。所以也许你错过了别的东西?
希望这会有所帮助!
您在视图中使用的模型与您应用验证的模型不同。它应该是'@model InfoFormulaireEmployeModele'。 – DCruz22
糟糕,我纠正了这一点。我对代码进行了一些修改,因此它更小,并且没有一堆法语变量。 –
但是,您确定这是您正在使用的代码吗?您的视图和模型中的属性命名方式不同。您只需将代码添加到当前的模型,视图和控制器中以避免混淆。 – DCruz22