0

Does anyone know how I could use JavaScript with a checkbox in order to hide one ajax ActionLink and display another when the checkbox is checked?

View:

@Html.Label("Title")
@Html.CheckBox("CheckBox")

@Ajax.ActionLink("Do Stuff1", "SoStuff1", new { Id = Model.Id }, new AjaxOptions{//ajaxoptions},

@Ajax.ActionLink("Do Stuff2", "SoStuff2", new { Id = Model.Id }, new AjaxOptions{//ajaxoptions},

Thanks

devC
  • 49
  • 3
  • 9
  • If you show your HTML you might not need JavaScript. – David Thomas Jan 16 '14 at 14:38
  • I don't have it at hand, it's standard HTML view for a MVC4 app. What in the HTML could determine if I don't need to use JavaScript? – devC Jan 16 '14 at 14:43
  • He is showing the HTML that is MVC for actionlinks using razer syntax – Charles380 Jan 16 '14 at 15:06
  • is it possible to assign different ID for the two action links? if it is, just do a regular jquery stuff. fx: $('#actionlinkid').hide() and $('#actionlinkid').show() on check box checked event. – Reza.Hoque Jan 16 '14 at 15:28
  • @devC: the structure of the DOM, I don't know how that syntax typically renders, but if it's predictable then 'view source' should give the relevant output. – David Thomas Jan 16 '14 at 15:38
  • @DavidThomas: how in the world would the OP never not need JavaScript to show/hide something based on a checkbox. The mere description of the problem screams the need for JavaScript. – Chris Pratt Jan 16 '14 at 15:39
  • @Chris: HTML and CSS can definitely (within certain constraints) do this, for example: http://stackoverflow.com/a/19755019/82548 and it's those constraints that make the rendered HTML necessary. – David Thomas Jan 16 '14 at 16:11

1 Answers1

0

Ajax.ActionLink has no overload that allows passing custom HTML attributes, and it's going to be hard to show/hide one or the other without being able to reference some id or class. You could, I suppose, wrap the link in a div or span, and then apply an id or class to that. That would actually probably be the safest and quickest course.

Once you have something you can select with, the JavaScript is trivial (I should say "the jQuery", as I always hate it when other people equate the two. But, ASP.NET MVC uses jQuery by default, so support can be assumed.):

$('#CheckBox').on('click', function () {
    if ($(this).is(':checked')) {
        $('#link1').show();
        $('#link2').hide();
    } else {
        $('#link1').hide();
        $('#link2').show();
    }
});

FWIW, I would caution against the entire gamut of Ajax helpers. Automagic code is great, but automagic AJAX code, I believe, is a step too far. There's too much going on there and it's all hidden from the developer. That's a recipe for disaster.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444