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?
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With