Подтвердить что ты не робот

Как добавить "обязательный" атрибут в редактор ввода текста mvc 5 razor view

У меня есть следующий помощник HTML MVC 5 Razor:

@Html.TextBoxFor(m => m.ShortName, 
  new { @class = "form-control", @placeholder = "short name"})

Мне нужно, чтобы это поле было необходимо (т.е. иметь красный контур, когда пользователь переходит, не помещая значение inn). В HTML 5 WebForms я мог бы просто сказать <input type="text" required />, чтобы иметь этот эффект. Каков правильный синтаксис для выполнения этого в синтаксисе Razor?

4b9b3361

Ответ 1

Вы можете использовать атрибут required html, если хотите:

@Html.TextBoxFor(m => m.ShortName, 
new { @class = "form-control", placeholder = "short name", required="required"})

или вы можете использовать класс RequiredAttribute в .Net. С помощью jQuery RequiredAttribute может проверяться на лицевой стороне и на стороне сервера. Если вы хотите пройти маршрут MVC, я бы предложил прочитать Аннотации данных MVC3 Обязательный атрибут.

ИЛИ

Вы можете получить действительно продвинутый:

@{
  // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
  var attributes = new Dictionary<string, object>(
    Html.GetUnobtrusiveValidationAttributes(ViewData.TemplateInfo.HtmlFieldPrefix));

 attributes.Add("class", "form-control");
 attributes.Add("placeholder", "short name");

  if (ViewData.ModelMetadata.ContainerType
      .GetProperty(ViewData.ModelMetadata.PropertyName)
      .GetCustomAttributes(typeof(RequiredAttribute), true)
      .Select(a => a as RequiredAttribute)
      .Any(a => a != null))
  {
   attributes.Add("required", "required");
  }

  @Html.TextBoxFor(m => m.ShortName, attributes)

}

или если вам это нужно для нескольких шаблонов редактора:

public static class ViewPageExtensions
{
  public static IDictionary<string, object> GetAttributes(this ViewWebPage instance)
  {
    // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
    var attributes = new Dictionary<string, object>(
      instance.Html.GetUnobtrusiveValidationAttributes(
         instance.ViewData.TemplateInfo.HtmlFieldPrefix));

    if (ViewData.ModelMetadata.ContainerType
      .GetProperty(ViewData.ModelMetadata.PropertyName)
      .GetCustomAttributes(typeof(RequiredAttribute), true)
      .Select(a => a as RequiredAttribute)
      .Any(a => a != null))
    {
      attributes.Add("required", "required");
    }
  }
}

то в ваших шаблонах:

@{
  // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
  var attributes = this.GetAttributes();

  attributes.Add("class", "form-control");
  attributes.Add("placeholder", "short name");

  @Html.TextBoxFor(m => m.ShortName, attributes)

}

Ответ 2

В вашем классе модели украсить это свойство атрибутом [Required]. То есть:.

[Required]
public string ShortName {get; set;}

Ответ 3

Мне нужен "необходимый" атрибут HTML5, поэтому я сделал что-то вроде этого:

<%: Html.TextBoxFor(model => model.Name, new { @required = true })%>

Ответ 4

Более новый способ сделать это в .NET Core с TagHelpers.

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro

Основываясь на этих примерах (MaxLength, Ярлык), вы можете расширить существующий TagHelper в соответствии с вашими потребностями.

RequiredTagHelper.cs

using Microsoft.AspNetCore.Razor.TagHelpers;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.Linq;

namespace ProjectName.TagHelpers
{
    [HtmlTargetElement("input", Attributes = "asp-for")]
    public class RequiredTagHelper : TagHelper
    {
        public override int Order
        {
            get { return int.MaxValue; }
        }

        [HtmlAttributeName("asp-for")]
        public ModelExpression For { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output); 

            if (context.AllAttributes["required"] == null)
            {
                var isRequired = For.ModelExplorer.Metadata.ValidatorMetadata.Any(a => a is RequiredAttribute);
                if (isRequired)
                {
                    var requiredAttribute = new TagHelperAttribute("required");
                    output.Attributes.Add(requiredAttribute);
                }
            }
        }
    }
}

Затем вам необходимо добавить его для использования в ваших представлениях:

_ViewImports.cshtml

@using ProjectName
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, ProjectName"

Учитывая следующую модель:

Foo.cs

using System;
using System.ComponentModel.DataAnnotations;

namespace ProjectName.Models
{
    public class Foo
    {
        public int Id { get; set; }

        [Required]
        [Display(Name = "Full Name")]
        public string Name { get; set; }
    }
}

и просмотр (фрагмент):

New.cshtml

<label asp-for="Name"></label>
<input asp-for="Name"/>

В результате получится HTML:

<label for="Name">Full Name</label>
<input type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value="" required />

Я надеюсь, что это полезно для тех, у кого есть тот же вопрос, но с использованием .NET Core.

Ответ 5

@Ответ Эрика не летал для меня.

Следующее сделано:

 @Html.TextBoxFor(m => m.ShortName,  new { data_val_required = "You need me" })

плюс делать это вручную под полем, мне пришлось добавить контейнер сообщений

@Html.ValidationMessageFor(m => m.ShortName, null, new { @class = "field-validation-error", data_valmsg_for = "ShortName" })

Надеюсь, это сэкономит вам некоторое время.