简体   繁体   English

简化ASP.Net MVC剃刀代码

[英]Simplifying ASP.Net MVC Razor Code

I'm looking for suggestions on how to simplify/optimize a piece of code in one of my view files in my ASP.Net MVC project. 我正在寻找有关如何在ASP.Net MVC项目中的一个视图文件中简化/优化代码的建议。 The code works, but I'm not sure if I've written it the best way. 该代码有效,但是我不确定是否编写了最佳方法。

Basically, the code is used to display a list of links to documents, with little thumbnails to the left of each link. 基本上,该代码用于显示文档链接的列表,每个链接的左侧都有一些缩略图。 The main problem, is that there are two different types of documents, and each type has to have it's thumbnail image stored in a different location, this is a project requirement and can't be changed. 主要问题是有两种不同类型的文档,每种类型的文档都必须将其缩略图存储在不同的位置,这是项目要求,不能更改。

I'm currently accomplishing this with the view code shown below. 我目前正在用下面显示的查看代码完成此操作。

// Display a link to every document.
foreach (var document in documentList)
{
    <a href="@Url.Content("~/Document/DownloadDocument/" +
        document.documentid)" target="_blank">
    @{
        // This will be the root of all the paths.
        var path = "~/Document/DisplayImage/";

        // If it's a Type 1 document, we need to use a different path.
        if (document.documentType == "Type 1") {
            path += "Path/To/Image/Folder";

            <img id="imageHolder" src="@Url.Content(path)"
                 onerror="imgError(this);" />
            @document.documentname
        }
        else {
            path += "Path/To/Different/Image/Folder";

            <img src="@Url.Content(path)" />
            @document.documentname
        }
    }
    </a>
    <br />
}

Like I said, the code works, but I'm not too happy with how it's written. 就像我说的那样,代码有效,但是我对它的编写方式不太满意。 Does anyone have any suggestions? 有没有人有什么建议?

When working with MVC, it's best to keep your Views dumb (no logic, simply rendering). 使用MVC时,最好使您的View保持哑(无逻辑,只需渲染)。

You can accomplish this by using a strongly-typed View and performing all of the logic in the Controller. 您可以通过使用强类型的View并执行Controller中的所有逻辑来完成此操作。 It looks like you may already be doing this since you have a documentList . 由于您具有documentList因此您似乎已经在执行此操作。

In this case, documentList should be a list of View Model objects that already have the appropriate image path already set on them from the controller. 在这种情况下, documentList应该是视图模型对象的列表,这些视图模型对象已经从控制器设置了适当的图像路径。

I would suggest moving the path to your document image into your model. 我建议将文档图像的路径移动到模型中。 That way you can just display the image from the path in the model and you wouldn't have to put any logic in your view. 这样,您可以只显示模型中路径的图像,而不必在视图中添加任何逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM