您可以阅读以下有关编写自定义的文章
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) <input type="submit" value="OK" />}
最后是编辑器模板(
~/Views/Shared/EditorTemplates/string.cshtml):
@{ var placeholder = string.Empty; if (ViewData.Modelmetadata.AdditionalValues.ContainsKey("placeholder")) { placeholder = ViewData.Modelmetadata.AdditionalValues["placeholder"] as string; }}<span> @Html.Label(ViewData.Modelmetadata.PropertyName) @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { placeholder = placeholder })</span>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)