有没有办法使用@Html.EditorFor编写Html5 placeholder,或者我应该只使用TextBoxFor扩展名,即
@Html.TextBoxFor(model => model.Title, new { @placeholder = "Enter title here"})
或者,编写我们自己的自定义扩展以通过DataAnnotation(类似于this)使用"description"显示属性是否有意义?
当然,同样的问题也适用于"自动对焦".
有没有办法使用@Html.EditorFor编写Html5 placeholder,或者我应该只使用TextBoxFor扩展名,即
@Html.TextBoxFor(model => model.Title, new { @placeholder = "Enter title here"})
或者,编写我们自己的自定义扩展以通过DataAnnotation(类似于this)使用"description"显示属性是否有意义?
当然,同样的问题也适用于"自动对焦".
你可以看看写定制DataAnnotationsModelMetadataProvider
的following article.
这是另一个,更多的ASP.NET MVC 3ish提供了新推出的IMetadataAware接口.
首先创建实现此接口的自定义属性:
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>