带有 .NET MVC 3 Razor EditorFor 扩展的 Html5 占位符? [英] Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

查看:31
本文介绍了带有 .NET MVC 3 Razor EditorFor 扩展的 Html5 占位符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用@Html.EditorFor 编写 Html5 占位符,或者我应该只使用 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 使用描述"显示属性(类似于 this)?

Or would it make sense to write our own custom extension that can maybe use the 'Description' display attribute via DataAnnotations (similar to this)?

当然,同样的问题也适用于自动对焦".

Of course, then the same question applies to 'autofocus' as well.

推荐答案

你可以看看 以下文章,用于编写自定义 DataAnnotationsModelMetadataProvider.

You may take a look at the following article for writing a custom DataAnnotationsModelMetadataProvider.

这是另一种更 ASP.NET MVC 3ish 的方式来处理新引入的​​ 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" />
}

最后是编辑器模板(~/Views/Shared/EditorTemplates/string.cshtml):

And finally the editor template (~/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>

这篇关于带有 .NET MVC 3 Razor EditorFor 扩展的 Html5 占位符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆