asp.net-mvc – 如何添加“必需”属性到mvc 5剃刀视图文本输入编辑器

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何添加“必需”属性到mvc 5剃刀视图文本输入编辑器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下MVC 5 Razor HTML助手:
@Html.TextBoxFor(m => m.ShortName,new { @class = "form-control",@placeholder = "short name"})

我需要这个字段是必需的(即当用户导航而不放置价值旅馆时,有一个红色的轮廓)。在WebForms HTML 5中,我只能说< input type =“text”required />有这个效果
使用Razor语法完成此功能的正确语法是什么?

解决方法

如果需要,您可以使用所需的html属性
@Html.TextBoxFor(m => m.ShortName,placeholder = "short name",required="required"})

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

要么

你可以得到真正的进步:

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

}
原文链接:https://www.f2er.com/aspnet/252880.html

猜你在找的asp.Net相关文章