Search code examples
ajaxasp.net-mvc-2actionlink

ASP.NET MVC 2: prevent ajax action link from replacing the updateTarget


I use an ajax action link on a view, then bind a js function onto its onCompleted property. In this function, i get the response object, do some funny stuff, then write the message property to the updatetarget element.

The problem is, when it finishes its work on the oncompleted event, it writes the raw json response onto the updatetarget element, replacing the text i already written. I want to prevent it to write the raw response to the updatetarget. I'm aware of the InsertionMode property, but its useless to me because it appends text to the element one way or another.

The scripts i mentioned are below;

The code of the action link on view:

<%: Ajax.ActionLink("Delete", "Delete", 
 new { id = Model.Id, secretKey = Model.SecretKey }, 
 new AjaxOptions { OnComplete = "WriteJsonResultToElement", UpdateTargetId="commandResult" })
%>

The WriteJsonResultToElement function

function WriteJsonResultToElement(resultObject) {
updateTarget = resultObject.get_updateTarget();
obj = resultObject.get_object();
$(updateTarget).text(obj.message); // here i set the text of update target
if (obj.result > 0)
    $('*:contains("' + obj.id + '")').last().parent().remove();
}

My JsonResult Delete method returns this data after action:

{"message":"Deleted","result":1,"id":132}

Thanks.


Solution

  • If you don't want the raw JSON response appended to the DOM don't specify an UpdateTargetId:

    <%: Ajax.ActionLink(
        "Delete", 
        "Delete", 
        new { id = Model.Id, secretKey = Model.SecretKey }, 
        new AjaxOptions { OnComplete = "success" })
    %>
    

    and handle it in the success callback:

    function success(result) {
        var obj = result.get_object();
        alert(obj.message);
        // TODO: do something with the object
    }