HTML5占位符使用.NET MVC 3剃须刀EditorFor延期? [英] Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?
问题描述
有没有写 Html5的占位符使用@ Html.EditorFor的一种方式,或者我应该只使用TextBoxFor扩展即
Is there a way to write the Html5 placeholder using @Html.EditorFor, or should I just use the TextBoxFor extension i.e.
@Html.TextBoxFor(model => model.Title, new { @placeholder = "Enter title here"})
或者,它将使感写我们这也许可以使用通过DataAnnotations说明显示属性(类似于<一个自定义的扩展href=\"http://blogs.planetcloud.co.uk/mygreatdiscovery/post/Creating-tooltips-using-data-annotations-in-ASPNET-MVC.aspx\">this)?
当然,那么同样的问题适用于自动对焦,以及
Of course, then the same question applies to 'autofocus' as well.
推荐答案
您可以看一看的<一个href=\"http://aspadvice.com/blogs/kiran/archive/2009/11/29/Adding-html-attributes-support-for-Templates-_2D00_-ASP.Net-MVC-2.0-Beta_2D00_1.aspx\">following为编写自定义的文章 DataAnnotationsModelMetadataProvider
。
和这里进行,涉及新引入的 IMetadataAware 接口。
And here's another, more ASP.NET MVC 3ish way to proceed involving the newly introduced IMetadataAware interface.
通过创建一个自定义属性实现此接口启动:
Start by creating a custom attribute implementing this interface:
public class PlaceHolderAttribute : Attribute, IMetadataAware
{
private readonly string _placeholder;
public PlaceHolderAttribute(string placeholder)
{
_placeholder = placeholder;
}
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues["placeholder"] = _placeholder;
}
}
然后用它装点你的模型:
And then decorate your model with it:
public class MyViewModel
{
[PlaceHolder("Enter title here")]
public string Title { get; set; }
}
接下来定义控制器:
Next define a controller:
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" />
}
最后编辑模板(〜/查看/共享/ 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>
这篇关于HTML5占位符使用.NET MVC 3剃须刀EditorFor延期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!