在C#中,我們通常使用ASP.NET MVC或Blazor等框架來構建Web應用程序。這些框架提供了內置的表單驗證功能,可以與Bootstrap一起使用以實現美觀且功能豐富的表單驗證。
以下是一個使用ASP.NET MVC和Bootstrap實現表單驗證的示例:
_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)
{
// 保存用戶數據,登錄用戶等
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")
}
這將創建一個具有客戶端和服務器端驗證的表單。當用戶提交表單時,將使用Bootstrap樣式顯示驗證錯誤消息。