views:

75

answers:

3

The current code of one of the views in my project is a large, monolithic one and I just want to organize it. Is it just fine to place methods inside my ASP.NET MVC view?

+1  A: 

It's possible but if you need methods inside a view, perhaps you should instead consider extending the Html object with an extension method, and then use these methods from inside the view. I like to separate my extensions by functionality to keep the view readable. For example:

public static MySpecialDateHelper SpecialDateHelper(this HtmlHelper helper)
{
    return new MySpecialDateHelper(helper);
}


public class MySpecialDateHelper
{
    // Fields
    private HtmlHelper m_helper;
    private StringBuilder m_sb = new StringBuilder();

    // Methods
    internal MySpecialDateHelper(HtmlHelper helper)
    {
        this.m_helper = helper;
    }

        // Print date prettily
        public public string PrettyDate(datetime target)
    {
        // format however
        return string.format("pretty {0}", target.ToString());
    }

    // Print date prettily
        public public string PrettyDateInATextbox(datetime target)
    {
        return m_helper.TextBox("prettyid",PrettyDate(target));
    }

    // etc...
}

Then in your view, you just have to reference the extension you just created

<%= Html.SpecialDateHelper.PrettyDateInATextbox(Now); %>

Of course, your separation of methods into extensions may vary, you can also extend the HtmlHelper object with the methods directly, but i prefer this method

samy
+5  A: 

I would say definitely not. The purpose of MVC is to separate the concerns i.e. Model - View - Controller. In your case you are mixing Model/Controller logic with your View.

If you need to pass complex content into your view you should create custom ViewData classes, populate them in your controller and pass them into your View.

If your methods are more relating to generating View markup you should look at splitting it up into partial views or as already suggested using helper extension methods.

James
+1  A: 

No.

Move it the controller, if necessary introduce view models. After the that, define your own Html helpers, considering those should be for html like stuff, not for any logic.

You could have something in a view that's v. v. specific to it, and its just not possible that bit of code would do anything outside of it. But even then, you can just define it in a helper, as long as the name is very clear on what it does, you are better than putting it in the view. You can unit test helpers, so there is a clear advantage when doing that.

eglasius