有没有一种方法可以使用@Html.EditorFor编写Html5 placeholder,或者我应该只使用TextBoxFor扩展。
@Html.TextBoxFor(model => model.Title, new { @placeholder = "Enter title here"})
或者,编写我们自己的自定义扩展,或许可以通过DataAnnotations (类似于this)使用“Description”显示属性,这有意义吗?
当然,同样的问题也适用于“自动聚焦”。
发布于 2011-04-29 03:53:39
您可以查看一下用于编写自定义DataAnnotationsModelMetadataProvider
的following article。
这里是另一种更像ASP.NET MVC3ish的方式,涉及到新引入的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>
发布于 2014-07-18 06:06:56
实际上,我更喜欢在大多数情况下使用占位符文本的显示名称。以下是使用DisplayName的示例:
@Html.TextBoxFor(x => x.FirstName, true, null, new { @class = "form-control", placeholder = Html.DisplayNameFor(x => x.FirstName) })
发布于 2014-12-30 18:24:11
我在资源文件中使用这种方法(不再需要提示!)
@Html.TextBoxFor(m => m.Name, new
{
@class = "form-control",
placeholder = @Html.DisplayName(@Resource.PleaseTypeName),
autofocus = "autofocus",
required = "required"
})
https://stackoverflow.com/questions/5824124
复制相似问题