如何在 asp mvc 中的 cshtml razor 文件中设置正则表达式?

How to set regular expressions in cshtml razor file in asp mvc?

我想在我的 cshtml 文件中设置正则表达式,请帮我看看我是怎么做到的?我不想先在代码中使用正则表达式。

<div class="form-group">
    @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })

    <div class="col-md-10">
       @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control", placeholder = "short name", required = "required", RegularExpressionAttribute = @"^([a-zA-Z .&'-]+)$" } })
       @Html.ValidationMessageFor(model => model.Title,"", new { @class = "text-danger" })
    </div>
</div>

这行得通。您需要将 EditorFor 更改为 TextBoxFor。删除 htmlAttributes,并使用模式代替 RegularExpressionAttribute:

型号:

namespace Testy20161006.Models
{
    public class Student
    {
        public int ID { get; set; }
        public String Name { get; set; }
        public String email { get; set; }
    }

}

控制器:

    [HttpPost]
    public ActionResult Index9(Student stud)
    {
        if (ModelState.IsValid)
        {
            var ap = "dh";
        }
        return View(stud);
    }

    public ActionResult Index9()
    {
        return View(new Student());
    }

查看:

@model Testy20161006.Models.Student

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index9</title>
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <link href="~/Content/Student.css" rel="stylesheet" />
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.TextBoxFor(model => model.Name, new { @class = "form-control", placeholder = "short name", required = "required", pattern = @"^([a-zA-Z .&'-]+)$"  })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            <input type="submit" value="Submit" />
        }
    </div>
</body>
</html>