Asp.net-Mvc

如何將“必需”屬性添加到 mvc razor viewmodel 文本輸入編輯器

  • April 14, 2014

我有以下 MVC 5 Razor HTML 助手:

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

我需要這個欄位(即當使用者在沒有輸入值的情況下導航出去時有一個紅色的輪廓)。在 WebForms HTML 5 中,我只能說<input type="text" required />有這種效果。在 Razor 語法中完成此操作的正確語法是什麼?

如果需要,可以使用requiredhtml 屬性:

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

或者您可以在.Net中使用RequiredAttribute類。使用 jQueryRequiredAttribute可以在前端和伺服器端進行驗證。如果你想走 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 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 )。

ViewData 和 ViewBag 有什麼區別?

摘抄:

所以基本上它(ViewBag)替換了魔術字元串:

ViewData["Foo"]

具有魔法屬性:

ViewBag.Foo

引用自:https://stackoverflow.com/questions/23071795