温馨提示×

C#中Bootstrap的表单验证实现

c#
小樊
81
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