在C#中,我們通常使用ASP.NET MVC或Blazor等框架來構(gòu)建Web應(yīng)用程序。這些框架提供了內(nèi)置的表單驗(yàn)證功能,可以與Bootstrap一起使用以實(shí)現(xiàn)美觀且功能豐富的表單驗(yàn)證。
以下是一個(gè)使用ASP.NET MVC和Bootstrap實(shí)現(xiàn)表單驗(yàn)證的示例:
_Layout.cshtml
文件中添加以下代碼以引入Bootstrap CSS和JS文件:<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
User
的類:public class User
{
[Required]
public string Name { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
public class HomeController : Controller
{
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(User user)
{
if (ModelState.IsValid)
{
// 保存用戶數(shù)據(jù),登錄用戶等
return RedirectToAction("Index");
}
return View(user);
}
}
Register.cshtml
文件中添加以下代碼:@model YourNamespace.User
<div class="container">
<h2>Register</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
</div>
<button type="submit" class="btn btn-primary">Register</button>
}
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
這將創(chuàng)建一個(gè)具有客戶端和服務(wù)器端驗(yàn)證的表單。當(dāng)用戶提交表單時(shí),將使用Bootstrap樣式顯示驗(yàn)證錯(cuò)誤消息。