如何在mvc razor viewmodel文本输入编辑器中添加“required”属性

时间:2014-04-14 22:53:55

标签: asp.net-mvc razor data-annotations html-helper

我有以下MVC 5 Razor HTML帮助器:

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

我需要这个字段是必需的(例如,当用户导航而没有放置值值时,会有一个红色轮廓)。在WebForms HTML 5中,我可以说<input type="text" required />具有此效果。 在Razor语法中实现此目的的正确语法是什么?

5 个答案:

答案 0 :(得分:71)

如果需要,您可以使用required html属性:

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

或者您可以在.Net中使用RequiredAttribute类。使用jQuery,RequiredAttribute可以在前端和服务器端验证。如果你想进入MVC路线,我建议你阅读Data annotations MVC3 Required attribute

OR

你可以变得非常高级:

@{
  // 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 WebViewPage 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)

}

更新1(对于不熟悉ViewData的Tomas)。

What's the difference between ViewData and ViewBag?

摘录:

  

所以基本上它(ViewBag)取代了魔术字符串:

ViewData["Foo"]
     

具有魔法属性:

ViewBag.Foo

答案 1 :(得分:19)

在您的模型类中使用[Required]属性装饰该属性。即:

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

答案 2 :(得分:6)

在.NET Core中执行此操作的新方法是使用TagHelpers

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

在这些示例(MaxLengthLabel)的基础上,您可以扩展现有的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 required type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value=""/>

我希望这对任何有相同问题但使用.NET Core的人都有帮助。

答案 3 :(得分:2)

我需要&#34;必需&#34; HTML5属性,所以我做了这样的事情:

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

答案 4 :(得分:0)

@Erik的答案不适合我。

以下是:

 @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" })

希望这可以节省你一些时间。