Search code examples
asp.net-mvcfunctional-programmingprocedural-programming

MVC Razor Display Data in Groups


I keep falling back to procedural programming when displaying data in groups and I am sure that there must be a better way. Your thoughts?

//Example: Sales by Region

@{
    string _Region = "";
    bool _FirstRecordFlag = false;
    }


    @foreach(DataRow Row in dataset.Tables["MonthlySales"].Rows)
    {
        if(_Region != Row["Region"].ToString())
        {
           if(_FirstRecordFlag)
            {
                @:</fieldset>
                _FirstRecordFlag = true;
            }
            @:<fieldset>
            @:  <legend>@Row["Region"]</legend>
            _Region = Row["Region"].ToString())
        }
            <div>
                Display Sales data here...
            </div>
    }
}

Solution

  • I keep falling back to procedural programming when displaying data in groups and I am sure that there must be a better way

    Of course that there is a better way. Since your question is tagged with mvc, you should use a view model and perform all this sort of grouping in the controller to populate your view model which will be passed to the view. The Razor view should then be as dumb as possible - it will only display the information from the view model. Working with DataSets and DataRows in a Razor view is just absolutely the wrong way to approach this problem. Your views will resemble like some horrible spaghetti code.

    So think in terms of how you want to present the information on the view. Based on this thinking you will be able to come up with a view model which will reflect this structure. Then all you have to do in the controller action is to map your domain models (DataSets in your case) to the corresponding view model which will be passed to the view.

    And if this is not an ASP.NET MVC application but a WebMatrix site where you only have the View part, you should still define a view model and have your code-behind part of the razor page map the domain model to the view model which will then be manipulated by the view part of the Razor template.