Reputation: 83
I have a Markdown editor in my MVC 5 application.Here is the code:
<script type="text/javascript">
var executivesummary = new tui.Editor({
el: document.querySelector('#Recommendation'),
previewStyle: 'vertical'})
I have save function to save the contents of the editor like this
function saveContent(e) {
var contents = Recommendation.GetValue();
console.log(content)
e.preventDefault();
}
I have a field in Model with get and set,i want to update this value "contents" to the Model. How to do this?
Upvotes: 1
Views: 2971
Reputation: 228
You need to make a call to an action method within your controller to update the model. Then you can reload the view (or parts of it) with Ajax (or using Ajax.BeginForm).
Some example ajax call:
$("#idToClickOn").click(function () {
var contents = @Html.Raw(Json.Encode(Recommendation.GetValue()));
$.ajax({
url: 'https://@(Request.Url.Host)/Controller/Action',
type: 'POST',
dataType: 'json',
data: contents,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
error: function (data) {
alert("error: " + data);
}
});
});
Some example with Ajax.BeginForm:
@using (Ajax.BeginForm("Action", new { Controller = "ControllerName", area = "" }, new AjaxOptions() { OnSuccess = "onSuccessLogin", HttpMethod = "POST", UpdateTargetId = "idInViewToUpdate"}, new { id = "formID" }))
{
...
<div>
@Html.Partial("Path to form body")
</div>
<button class="btn btn-primary btn-block">Save</button>
}
Your controller, something like:
[HttpPost]
[ValidateAntiForgeryToken]
[HandleError]
public ActionResult Action(YourModel model)
{
if (ModelState.IsValid)
{
do Something;
return PartialView("Path to your view");
}
else
{
return PartialView("Path to your view", model);
}
}
YourModel needs to fit the json you create, of course.
In that action, you can modify the model and reload the view.
Upvotes: 1