2016-12-13 6 views
-1

Я хочу установить регулярное выражение в моем файле cshtml, пожалуйста, помогите мне, как я это сделал? Я не хочу использовать регулярное выражение в коде первым.Как установить регулярные выражения в файле cshtml razor в asp mvc?

<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> 

ответ

2

Это работает. Вам нужно изменить 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> 
+0

благодаря его ответ работал @kblau –

+0

и как использовать сообщение проверки для шаблона не использовать: @ Html.ValidationMessageFor (model => model.Name, Resources.Milsa.Milsa_RequiredField, new {@class = "text-danger"}) –