ASP.NET MVCとCodebehind-filesについては多くの議論がありましたが、ほとんどの場合、これらのCodebehind-filesは悪であると指摘されています。
だから私の質問は、ページ固有のロジックをどのように処理するのですか?
ここで必要ないのは、インラインコード内のスパゲッティコードであり、ページ固有のコードがヘルパークラス全体またはHTMLヘルパークラスの上に散在することは望ましくありません。
例は次のとおりです。
<% for(int i = 0; i < companyList.Count; i++) { %>
RenderCompanyNameWithRightCapsIfNotEmpty(company, i)
<% } %>
コードビハインドを伴う:
private string RenderCompanyNameWithRightCapsIfNotEmpty(string company, index)
{
if (index == 0) {
return string.Format("<div class=\"first\">{0}</div>", company);
}
// Add more conditional code here
// - page specific HTML, like render a certain icon
string divClass = (index % 2 == 0) ? "normal" : "alternate";
return string.Format("<div class=\"{1}\">{0}</div>", company, divClass);
}
これは1ページでのみ使用され、変更される可能性があります。
更新:これらがどこにあるかについて私が考えたいくつかのアプローチ:
1)ページの後ろにあるインラインコード-文字列を返す単純なメソッドを使用します。
<script runat="server">
private string RenderCompanyHtml(string companyName) ...
<script>
2)文字列を返すメソッドをコントローラに配置します。しかし、それはView-logicをControllerに入れることになるでしょう。
public class SomeController : Controller
{
[NonAction]
private static string RenderCompanyHtml(string companyName) ...
public ActionResult Index() ...
}