gpt4 book ai didi

c# - 显示静态生成数据的 MVC 最佳实践

转载 作者:太空狗 更新时间:2023-10-30 00:24:01 28 4
gpt4 key购买 nike

问题背景:

我有一个两页的 MVC 4 网络应用程序。第一页的 View 当前将其数据手动输入到 View 中作为其静态,即没有任何内容从其关联的 Controller 方法传递到 View ,如图所示:

索引 Controller 方法:

Public ActionResult Index()
{
return View();
}

Index.cshtml View :

<div class="titleHeader">Welcome To This Test Example</div>

最佳实践:

上面的例子是否可以使用,或者我应该在 Index Controller 上生成一个 ViewModel 对象,填充静态数据然后将它返回给 View?如图所示:

Index Controller Index 方法与 ViewModel:

Public ActionResult Index()
{
HomePageVM homepageVM = new HomePageVM
{
WelcomeMessage = "Welcome To This Test Example";
};

return View(homepageVM);
}

Index.cshtml 现在绑定(bind)到 HomePageVM ViewModel:

@model TestPage.Models.HomePageVM

<div class="titleHeader">@Model.WelcomeMessage</div>

最佳答案

我认为(意见),静态数据最好使用Resource文件。

使用这些资源文件,您将能够轻松移植到多语言网站。

基本上您需要创建 resx 文件,将条目公开。

在您的 cshtml 中,您可以通过以下方式访问它:

<div class="titleHeader">@Resources.WelcomeMessage</div>

根据 UIThread 的文化信息,它能够选择适当的语言。

您可以在此处找到教程: http://www.codeproject.com/Articles/778040/Beginners-Tutorial-on-Globalization-and-Localizati

至于你的选择:

1) 确实没有必要为静态数据创建 ViewModel,除非您希望它在将来是动态的(尽管现在为将来的需求开发是个坏习惯)。

2) cshtml 中的硬编码字符串,这是可能的,但不适合多语言。我想提一下 1 个好处:非开发人员更容易更改 html。

关于c# - 显示静态生成数据的 MVC 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30798939/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com