开发者

Best practices for minimizing ASP.NET MVC inline code (tag soap)?

I am an experienced ASP.NET WebForm developer and trying to learn MVC. I am still not too excited about MVC because of the inline code process. At some point I can't see the HTML from all the code and I have to render the page and do a view source.

I know you can swap out the view engine and was wondering about two things:

1- Is there a view engine which use开发者_如何转开发s less inline code than the default view engine? (Actually a resource doing a view engine comparison is helpful)

2- Is there a good resource explaining best practices for coding inline code for the view? I might be coding unnecessary code or over doing it.

3- What does ASP.NET MVC v2 offer in terms of view functionality more than previous version?


I've been using the Spark view engine for some time and have never looked back. Although it doesn't inherently reduce the amount of server-side code used on a View (that's something you'll have to do yourself), it can make it "blend-in" to the surrounding HTML, making the markup easier to read. Here's an example of it from the current project I'm working on (class and property names have been changed to protect the guilty):

<div id="Messages" if="Model.Messages.Count > 0">
    <MessageDetails each="Message message in Model.Messages" />
</div>

What you're basically seeing here is a) a wrapper <div> tag output to the View if there are Messages in the list (in this case, Model.Messages) and b) a rendered Partial View (called "MessageDetails") for each item in the list. The equivalent Web forms version would be something like:

<% if (Model.Messages.Count > 0) { %>
    <div id="Messages">
    <% foreach(Message message in Model.Messages) { %>
        <% Html.RenderPartial("Container", message); %>
    <% } %>
    </div>
<% } %>

While this doesn't always reduce the number of lines it takes to perform server-side actions (such as rendering a Partial View), it reduces the visual complexity of the View and makes the non-server-side markup much more maintainable.


The best practice for using the built in views is to use HTML helper extensions and partial views.

Personally, I like the fact that you are forced to encapsulate your UI code into helper classes and methods instead of superficially hiding it in a code behind file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜