Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use ACE with my ASP.NET MVC application?

I want to use the ACE online code editor in my project. How do I use it in ASP.NET MVC?

I'd like to save whatever edits are made with that editor in the database. How do I do that?

like image 387
beratuslu Avatar asked Dec 01 '11 15:12

beratuslu


2 Answers

Let's assume you have a strong typed model with a property called Editor with the data in it. Now use a normal <div> to load the data:

<div id="editor"><%=Model.Editor %></div>

Now you can create an ace editor in place of the div with javascript:

<script src="src/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
window.onload = function() {
    var editor = ace.edit("editor");
};
</script>

Now when you want to save the data, for instance via a form post, use something like this to bind it back to the Editor property of the model:

<%=Html.HiddenFor(m=>m.Editor, new { @id = "hidden_editor" }) %>

<!-- this is jQuery, but you can use any JS framework for this -->
<script>
    $("form").submit(function () {
        $("#hidden_editor").val(editor.getSession().getValue());
    });
</script>

In your controller you can now save the data to the database

[HttpPost]
public ActionResult Index (IndexModel model) {
    var data = model.Editor;
    // save data in database
}
like image 56
Jan Jongboom Avatar answered Oct 27 '22 22:10

Jan Jongboom


Here is a solution using most recent technologies (Razor/MVC/Ajax) :

    $(document).ready(function() {
        $("#btnSave").on("click", function () {                
                $.ajax({
                    url: '@Url.Action("YourAction", "YourController")',
                    type: 'POST',
                    data: { id: @Model.ID,
                            html: ace.edit("editor").getValue() },
                    cache: false,
                    success: function (response) {
                        alert("Changes saved.");
                    }                        
                });
        });
    });

In Controller :

    [AjaxAuthorize]
    [HttpPost, ValidateInput(false)]
    public ActionResult YourAction(string id, string html)
    {
        if (id == null || String.IsNullOrEmpty(id))
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        // do you stuff
    }
like image 1
JP Tétreault Avatar answered Oct 27 '22 23:10

JP Tétreault