I have list of divs with some data in there:
<div style="border: 1px solid #dddddd;">
<div id="wrap">
<h3 id="cText">@Model.CommentText</h3>
<a id="runEdit" href="#" >Edit</a>
</div>
</div>
When user click on runEdit link I make edit from this:
e.preventDefault();
var txt = $('#cText').text();
$('#cText').remove();
$('#wrap').prepend('<textarea>' + txt + '</textarea>');
$('#wrap').append('<input type="submit" value="Ok" />');
$('#wrap').append('<input type="submit" value="Cancel" />');
The problem is I added here this two buttons in javascript. But I don’t know how to attach some controller action to this buttons?
The problem here is that if I write 5 comments. And click on edit I get 5 edit forms.
$('#editButton').live('click', function (e) {
e.preventDefault();
var container = $(this).closest('.commentWrap');
var itemId = container.attr('id');
var nestId = '#' + itemId;
var txt = $('#commentTextValue').text();
$(nestId + ' #commentTextValue').remove();
$(nestId + ' #editButton').remove();
$(nestId).prepend('<textarea id="editArea">' + txt + '</textarea>');
$(nestId).append('<input type="submit" value="Ok" class="btnOk" />');
})
$('.btnOk').live('click', function (e) {
e.preventDefault();
var container = $(this).closest('.commentWrap');
var itemId = container.attr('id');
var text = container.find('textarea').val();
var nestId = '#' + itemId;
//alert(nestId);
$.ajax({
url: '/Comment/SaveComment',
data: JSON.stringify({ CommentText: text, CommentId: itemId }),
type: 'post',
contentType: 'application/json',
success: function (data) {
if (data.success === true) {
//alert(data.message); // do show/hide stuff here instead of the alert
$(nestId + ' #editArea').remove();
$(nestId + ' .btnOk').remove();
$(nestId).append('<h3 id="commentTextValue">' + data.message + '</h3>');
$(nestId).append('<a id="editButton" href="#">Edit</a>');
}
}
});
});
</script>
<div style="border: 1px solid #dddddd;">
@Html.ActionLink(@Model.Author, "SomeAction")
<div class="commentWrap" id="@Model.CommentId">
<p id="commentTextValue">@Model.CommentText</p>
<a id="editButton" href="#">Edit</a>
</div>
</div>
First add an itemid to the div like this, and convert the id=wrap to a class, as there are more than one of them.
That way you get a way to reference the id of the item that you are editing.
You should also add a class to the submit button that you inject on the page, fx:
Then you can hook up the javascript:
NOTE: Download the json2 library and add it to you script references – it’s a good way to do your json serialization. (https://github.com/douglascrockford/JSON-js)
In your controller you must add an action method to handle the request: