1110
1110

Reputation: 6829

Asp mvc jquery - in place edit

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>

Upvotes: 2

Views: 1908

Answers (4)

Christian Dalager
Christian Dalager

Reputation: 6643

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.

<div class="wrap" id="123"></div>

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:

<input type="submit" class="btnOk" value="Ok"/>

Then you can hook up the javascript:

$('.btnOk').live('click',function(e){
   e.preventDefault();
   var container = $(this).closest('.wrap');
   var itemId = container.attr('id');
   var text = container.find('textarea')[0].val();
   $.ajax({
     url: '/mycontroller/savecomment',
     data: JSON.stringify({comment: text, id:itemId}), // using JSON2, see below
     type: 'post',
     contentType: 'application/json',
     success: function(data){
       if(data.success===true){
          alert(data.message); // do show/hide stuff here instead of the alert

        }
     }
   });

}); 

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:

    public ActionResult SaveComment(string text, int id)
    {
        //save your comment for the thing with that id
        var result = new {success = true, message = "saved ok"};
        return Json(result, JsonRequestBehavior.AllowGet);
    }

Upvotes: 4

Oybek
Oybek

Reputation: 7243

The answer of Marc is collrect. Surround your code with this. However I strongly recommend you to make as much "html in html" rather than in JavaScript.

The above code could be translated to a better shape, like this,

<div style="border: 1px solid #dddddd;">        
    <div id="wrap">
    <h3  id="cText">@Model.CommentText</h3>   
    <a id="runEdit" href="#" >Edit</a> 
    </div>
    <div id="editPanel" style="display:none;">
        <form action="@Url("Edit", "Whatevercontroller")">
            <textarea name="CommentText">@CommentText</textarea>
            <input type="submit" value="Ok" />
            <a href="#" id="cancelEdit">Cancel</a>
        </form>
    </div>
</div>

and js would be

function StartEdit() {
    $("#wrap").css("display", "none");
    $("#editPanel").css("display", "block");
}
function CancelEdit() {
    $("#wrap").css("display", "block");
    $("#editPanel").css("display", "none");
}

the advantage of this approach that you do not generate too much DOM elements in this case. Otherwise chances tha your JavaScript will become absolutely unmanageable.

Upvotes: 2

tugberk
tugberk

Reputation: 58444

You need to make Ajax calls to your controller action. Please refer to below link :

http://tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views

You will find a sample there.

Basically, what you need to do is as follows:

var d = "poo=1&bar=2";

$.ajax({
    type: "POST",
    url: "/home/myaction",
    data: d,
    success: function (r) {
        alert(r.data);
    },
    complete: function () {

        alert("I am done!");
    },
    error: function (req, status, error) {
        //do what you need to do here if an error occurs
        alert("error");
    }
});

Upvotes: 0

Marc
Marc

Reputation: 6771

You have to put a form tag around your textarea and to set the action of the form by the @Url.Action helper to the needed action.

Upvotes: 1

Related Questions