Search code examples
asp.net-mvcrazorcodemirror

Saving a tutorial with code in database


If I were to build a site that holds tutorials and articles for people to read, how would I go about saving a users text and the users sample code in the database. Knowing that the tutorial for example can show a paragraph explaining something then show some sample code, then show another paragraph of text describing something then show some more sample code? I'm using code mirror to format code and make it look good. I'm having a hard time figuring out how to save and then how to bring back down the info and know if the info is text or code. Any advice is appreciated. :)

So the format im looking for on the view: (should all this be in one coloumn? or separate field for code and for text?

---paragraph----

----...---------

---code---------


--more text-----

, and so on.


Solution

  • A list of content, each piece of content has a column to specify whether it is code, text or any other format you add in the future, and a column to store the text of the paragraph or code. You could use a binary blob for storage instead, which would allow you to support images, but then it becomes annoying to work with.

    public class Content {
       public string ContentType {get; set;}
       public string ContentText {get; set;}
    }
    public class Tutorial 
    {
       public IList<Content> Content {get;set;}
    }
    

    Razor

    @foreach(var content in Model.Content) {
       @Html.Partial(content.Type, content);
    }
    

    alternatively you could create a concrete per content type (which inherit from IContent) then use DisplayFor to render it, and a TPH table for storage.