ASP.NET MVC 3自定义HTML Helpers-最佳实践/用途 [英] ASP.NET MVC 3 Custom HTML Helpers- Best Practices/Uses

查看:159
本文介绍了ASP.NET MVC 3自定义HTML Helpers-最佳实践/用途的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新来的MVC,并已通过asp.net网站上的教程运行。

New to MVC and have been running through the tutorials on the asp.net website.

它们包括自定义HTML助手的一个例子截断在一个表中显示的长文本。

They include an example of a custom html helper to truncate long text displayed in a table.

只是想知道其他的解决方案人都想出使用HTML佣工,如果有任何的最佳做法或事物使用它们避免创建时/。

Just wondering what other solutions people have come up with using HTML helpers and if there are any best practices or things to avoid when creating/using them.

作为一个例子,我正在考虑写一个自定义的助手,我需要在不同的地方来显示日期格式,但现在很担心,有可能是一个更优雅的解决方案(即。DataAnnotations我的模型)

As an example, I was considering writing a custom helper to format dates that I need to display in various places, but am now concerned that there may be a more elegant solution(I.E. DataAnnotations in my models)

有什么想法?

编辑:

另一个潜在用途我只是想字符串连接的...。
自定义助手可以采取用户ID作为输入,并返回用户的全名...
其结果可能是,这取决于这些领域的一些可用的形式(标题)(初)(中)(最后)的。仅仅是一个想法,我没有尝试过这样的事情呢。

Another potential use I just thought of...String concatenation. A custom helper could take in a userID as input and return a Users full name... The result could be some form of (Title) (First) (Middle) (Last) depending on which of those fields are available. Just a thought, I have not tried anything like this yet.

推荐答案

井格式化的<一的情况下href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.aspx\">DisplayFormat属性可能是一个很好的解决方案:

Well in the case of formatting the DisplayFormat attribute could be a nice solution:

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime Date { get; set; }

,然后简单:

@Html.DisplayFor(x => x.Date)

至于截取字符串而言的自定义HTML助手是一个很好的解决方案。

As far as truncating string is concerned a custom HTML helper is a good solution.

更新:

关于你编辑,自定义的HTML帮助可能会在这种情况下工作,但也有另一种方法,我很喜欢:视图模型。所以,如果在这期特别你总是会显示名称的串联,那么你可以定义视图模型:

Concerning your EDIT, a custom HTML helper might work in this situation but there's also an alternative approach which I like very much: view models. So if in this particular view you are always going to show the concatenation of the names then you could define a view model:

public class PersonViewModel
{
    public string FullName { get; set; }
}

现在控制器是要查询资料库,以获取模型,然后映射此模型将被传递到视图视图模式,使视图可以简单地 @ Html.DisplayFor(X = GT; x.FullName)。模型和视图模型之间的映射关系可以与像 AutoMapper 框架可以简化。

Now the controller is going to query the repository to fetch the model and then map this model to a view model which will be passed to the view so that the view could simply @Html.DisplayFor(x => x.FullName). The mapping between models and view models could be simplified with frameworks like AutoMapper.

这篇关于ASP.NET MVC 3自定义HTML Helpers-最佳实践/用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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