加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 00:40:01 所属栏目:asp.Net 来源:网络整理
导读:我有以下MVC 5 Razor HTML助手: @Html.TextBoxFor(m = m.ShortName,new { @class = "form-control",@placeholder = "short name"}) 我需要这个字段是必需的(即当用户导航而不放置价值旅馆时,有一个红色的轮廓)。在WebForms HTML 5中,我只能说 input type
我有以下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)

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读