小编典典
您可以阅读以下有关编写自定义的文章DataAnnotationsModelMetadataProvider。
这是涉及新引入的IMetadataAware接口的另一种ASP.NET MVC 3ish更多方法。
首先创建一个实现此接口的自定义属性:
public class PlaceHolderAttribute : Attribute, IMetadataAware
{
private readonly string _placeholder;
public PlaceHolderAttribute(string placeholder)
{
_placeholder = placeholder;
}
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues["placeholder"] = _placeholder;
}
}
然后用它来装饰模型:
public class MyViewModel
{
[PlaceHolder("Enter title here")]
public string Title { get; set; }
}
接下来定义一个控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
}
相应的视图:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Title)
}
最后是编辑器模板(~/Views/Shared/EditorTemplates/string.cshtml):
@{
var placeholder = string.Empty;
if (ViewData.ModelMetadata.AdditionalValues.ContainsKey("placeholder"))
{
placeholder = ViewData.ModelMetadata.AdditionalValues["placeholder"] as string;
}
}
@Html.Label(ViewData.ModelMetadata.PropertyName)
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { placeholder = placeholder })
2020-05-10