Michael Tot Korsgaard
Michael Tot Korsgaard

Reputation: 4014

Better way to generate html in mvc4

Right now I have in my Mvc4 project a .cs class named HTMLcreator in my App_Code folder, which makes html for me to render in my views.

This I've heard is not the best way, and it's tiring to update the html elements in the .cs file.

What whould be a better way to create dynamic html for the view to use?


HTMLcreator.cs:

public static string methodOne()
    {
        StringBuilder result = new StringBuilder();
        List<Subjects> subjects = Subjects.GetAll(); // Gets a some objects

        foreach (Subjects s in subjects)
        {
            result.Append("<p>" + s.name + "</p>");

            if(s.hasChild)
            {
                result.Append(methodTwo(Subjects.GetChild(s)));
            }
        }
        return Convert.ToString(result);
    }

public static string methodTwo(Subjects s)
    {
        StringBuilder result = new StringBuilder();

        result.Append("<p>" + s.name + "</p>");

        if(s.hasChild)
        {
            result.Append(methodTwo(Subjects.GetChild(s)));
        }
        return Convert.ToString(result);
    }

The View calls the method with a @Html.Raw method.

Upvotes: 0

Views: 257

Answers (1)

haim770
haim770

Reputation: 49123

What you actually need here is a helper:

@helper methodOne(Subjects subjects)
{
    foreach (var subject in subjects)
    {
        <p>@subject.name</p>

        if (subject.hasChild)
            @methodOne(Subjects.GetChild(subject))
    }
}

Then use it somewhere in your View:

<div>
      @methodOne(subjects)
</div>

Yet, if you insist on generating the HTML yourself, your better use System.Web.Mvc.TagBuilder:

Contains classes and properties that are used to create HTML elements. This class is used to write helpers, such as those found in the System.Web.Helpers namespace.

See MSDN.

Upvotes: 2

Related Questions