質問

I am trying to limit how many characters of a url is going to be shown with annotations. I want the link be able to be very long it is only how it is displayed that I want to change. I could limit the length in every view that displays the url (Link), but I would prefer to change it only once in the model. I don't understand why this does not work. After adding the DisplayFormat annotation the url is shown as before without the length changing at all.

[Required()]
[DataType(DataType.Url)]
[DisplayFormat(DataFormatString = "{0,20}")]
public string Link { get; set; }
役に立ちましたか?

解決

Probably the best way to achieve it is to create your own template for your data type. One of possible solutions is to add ShortUrl.asxc or ShortUrl.cshtml to Shared\DisplayTemplates folder:

@model string

@Model.Substring(20)

And then change your field definition to:

[Required()]
[DataType(DataType.Url)]
[DisplayFormat(DataFormatString = "{0,20}")]
[UIHint("ShortUrl")]
public string Link { get; set; }

or provide template name in a view:

@Html.DisplayFor(m => m.Link, "ShortUrl")

Of course you could extend your display template to use metadata and check for nulls etc.,

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top