Comment ajouter l'attribut" required " à MVC razor viewmodel éditeur de texte
j'ai le MVC 5 Razor HTML helper suivant:
@Html.TextBoxFor(m => m.ShortName,
new { @class = "form-control", @placeholder = "short name"})
j'ai besoin que ce champ soit requis (i.e. avoir un contour rouge lorsque l'utilisateur navigue sans mettre de valeur DCI). Dans un WebForms HTML 5 je pourrais juste dire <input type="text" required />
pour avoir cet effet.
Quelle est la syntaxe appropriée pour accomplir ceci dans une syntaxe de rasoir?
5 réponses
vous pouvez utiliser l'attribut required
html si vous voulez:
@Html.TextBoxFor(m => m.ShortName,
new { @class = "form-control", placeholder = "short name", required="required"})
ou vous pouvez utiliser la classe RequiredAttribute .Net. Avec jQuery, le RequiredAttribute
peut être validé à l'avant et Côté Serveur. Si vous voulez suivre la route MVC, je vous conseille de lire annotations de données MVC3 attribut requis .
ou
Vous pouvez obtenir vraiment avancé:
@{
// 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)
}
ou si vous en avez besoin pour plusieurs modèles d'éditeur:
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");
}
}
}
puis dans vos gabarits:
@{
// 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)
}
sur votre classe de modèle décorez cette propriété avec l'attribut [Required]
. C'est-à-dire:
[Required]
public string ShortName {get; set;}
une nouvelle façon de le faire dans .NET Core est avec TagHelpers
.
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro
en vous basant sur ces exemples ( MaxLength , étiquette ), vous pouvez étendre le TagHelper
existant pour répondre à vos besoins.
Requerdtaghelper.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);
}
}
}
}
}
besoin de l'Ajouter pour être utilisé dans vos vues:
_ViewImports.cshtml
@using ProjectName
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, ProjectName"
étant donné le modèle suivant:
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; }
}
}
et view (snippet):
Nouveau.cshtml
<label asp-for="Name"></label>
<input asp-for="Name"/>
résultera en HTML:
<label for="Name">Full Name</label>
<input required type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value=""/>
j'espère que cela sera utile à tous ceux qui ont la même question mais qui utilisent .NET Core.
j'avais besoin de l'atribute "required" HTML5, donc j'ai fait quelque chose comme ça:
<%: Html.TextBoxFor(model => model.Name, new { @required = true })%>
la réponse de @Erik n'a pas marché pour moi.
suivit did:
@Html.TextBoxFor(m => m.ShortName, new { data_val_required = "You need me" })
plus faire cela manuellement sous le champ I a dû ajouter le conteneur de message d'erreur
@Html.ValidationMessageFor(m => m.ShortName, null, new { @class = "field-validation-error", data_valmsg_for = "ShortName" })
J'espère que cela vous fera gagner du temps.