溫馨提示×

C#中Bootstrap的表單驗證實現

c#
小樊
107
2024-09-02 13:30:16
欄目: 編程語言

在C#中,我們通常使用ASP.NET MVC或Blazor等框架來構建Web應用程序。這些框架提供了內置的表單驗證功能,可以與Bootstrap一起使用以實現美觀且功能豐富的表單驗證。

以下是一個使用ASP.NET MVC和Bootstrap實現表單驗證的示例:

  1. 首先,確保已安裝并引用了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>
  1. 創建一個模型類,用于表示表單數據。例如,創建一個名為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; }
}
  1. 在控制器中創建一個操作方法,用于處理表單提交:
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);
    }
}
  1. 創建一個視圖,用于顯示表單。在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樣式顯示驗證錯誤消息。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女