Simple html vs extension methods in Razor (preference)

妖精的绣舞 提交于 2020-01-03 09:45:18

问题


For Simple tags in MVC Razor do you prefer to use simple HTML or use extension methods eg

<label for="male">Male</label> 
Or   
@Html.Label("male", "Male")

I feel it is sometime more easier to use the simple HTML. Extension methods make sense when you want to do some custom code.


回答1:


Depends. If the male element you are associating this label to is rendered with a html helper like: @Html.TextBoxFor(x => x.Male) then I would use a Html.LabelFor and keep the lambdas and strong typing. Also I would never use:

@Html.Label("male", "Male")

I would use a view model and a strongly typed version:

@Html.LabelFor(x => x.Male)

and I would decorate my view model property with the [DisplayName] attribute so that I can control message on my view model:

[DisplayName("foo bar")]
public string Male { get; set; }

So there are like many different possible scenarios. I could also sometimes simply use static HTML and no helpers (currently can't think of such scenario but I am sure it exists).




回答2:


You could use DisplayFor. It's another way to show your data.



来源:https://stackoverflow.com/questions/6654635/simple-html-vs-extension-methods-in-razor-preference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!