1

I'm new to jquery and ajax - just can't seem to get this to work! See my related question: Use Json and AjaxLink to Toggle Link Values in ASP.NET MVC 2

Here's my jquery:

$(function () {
    $("div[id^=add]").click(function (ev) {
        ev.preventDefault();
        updateMe(this.id.split('_')[1], "AddRequirement");
    });

    $("div[id^=remove]").click(function (ev) {
        ev.preventDefault();
        updateMe(this.id.split('_')[1], "RemoveRequirement");
    });
});


function updateMe(myId, myAction) {
    $.ajax({
        type: "POST",
        url: "AgreementType.aspx/" + myAction,
        data: 'aId=' + <%:Model.AgreementType.Id%> + '&rId=' + myId,
        dataType: "text",
        error: function(request, msg){
            alert( "Error upon saving request: " + msg );
        },
        success: function (data) {
            alert(data);
        }
    }); 
}

Currently I have a two different divs. A foreach loop determines which one to display:

<%if(req.Agreements.Any(r => r.AgreementTypeId == Model.AgreementType.AgreementTypeId))
    {%>
        <div id="<%:string.Format("remove_{0}", req.Id)%>" class="divLink">Remove</div>
    <% }
    else
    { %>
        <div id="<%:string.Format("add_{0}", req.Id)%>" class="divLink">Add</div>
    <%{%>

Here's my controller action. Pretty simple:

    public JsonResult AddRequirement(string aId, string rId)
    {
        string result = "Remove";
        //Code to add requirement

        return this.Json(result);
    }


    public JsonResult RemoveRequirement(string aID, string rID)
    {
        string result = "Add";
        //Code to remove requirement

        return this.Json(result);
    }
}

All the success function needs to do it update the innerHtml of the target with the contents, and change the id to match. Seems so easy! And yet I can't seem to figure it out. TIA

3
  • I'd prefer to just return a simple text string, which is why the controllers are JsonResult and the $ajax datatype is "text"; the controllers used to just return a string object. I've been tweaking this code for a while... Commented Dec 17, 2010 at 20:51
  • 1
    Thia line def looks wrong: url: "AgreementType.aspx/" + myAction Can your post your routing data from your global.asax? I am 100% you need to remove the .aspx from that line. Commented Dec 18, 2010 at 5:55
  • Nope, it's right. I had to add the .aspx in the routing so MVC would run on IIS 6: routes.MapRoute( "Default", // Route name "{controller}.aspx/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); Commented Dec 20, 2010 at 17:30

1 Answer 1

3

Finally - the code that works. This will allow the user to click on a div which will call a different controller method based on the contents of that div, in effect allowing you to toggle toggle elements of the object in a foreach loop. I'm sure it could be improved upon; for instance, I probably don't need to get the value of the div from the controller method, but at least it works.

Javascript

<script type="text/javascript">
    $(function () {
        $("div[class^=toggleLink]").click(function (ev) {
            ev.preventDefault();

            var divText = $('#' + this.id).text();

            if (divText == "Remove") {
                updateMe(this.id, "Remove");
            }
            else if (divText == "Add") {
                updateMe(this.id, "Add");
            }
        });
    });


function updateMe(myId, myAction) {
    $.ajax(
    {
        type: "POST",
        url: "/AgreementType/" + myAction,
        data: "aId=<%:Model.AgreementType.Id%>&rId=" + myId,
        success: function (result) {
            if (result.success) {
                $('div#' + myId).text(result.value);
            }
        },
        error: function (req, status, error) {
            alert(req + " " + status + " " + error);
        }
    });
}

</script>

Controller

    public ActionResult Add(string aId, string rId)
    {
        //Add to the template

        string result = "Remove";
        string nClass = "remLink";

        return Json(new { success = true, value = result, newClass = nClass });
    }


    public ActionResult Remove(string aID, string rId)
    {
        //Remove from the template

        string result = "Add";
        string nClass = "addLink";

        return Json(new { success = true, value = result, newClass = nClass });
    }

Markup

<% foreach(var req in std.Requirements)%>
   <% { %>
   <tr>
       <td>
       <%if(req.Agreements.Any(r => r.AgreementTypeId == Model.AgreementType.Id))
       {%>
           <div id="<%:req.Id%>" class="toggleLink">Remove</div>
       <% }
       else { %>
           <div id="<%:req.Id%>" class="toggleLink">Add</div>
       <%} %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.