2

Question: Why is cancel button posting to the controller like submit?

I have the form below loaded from a partial view. Submit works fine. The only thing I've been struggling with is why Cancel doesn't just dismiss the form. I've tried a variety of things like capturing the click event. I looked at http://jimmylarkin.net/post/2012/05/16/Broken-Validation-on-Cancel-Buttons-With-Unobtrusive-Validation-Ajax.aspx as a possible solution but I'm not sure this is the problem it's intended to address. No doubt it's some ignorance on my part. So what bonehead thing am I missing?

//click event loading the form. 
<script>
    $(document).ready(function () {
        $('#editbtn').click(function () {
            var url = "/Quiz/EditQuiz?id=@id";
            $.get(url, function (data) {
                $('#formdiv').html(data);
                $("#formdiv").show();
            });
        });  
</script>

//form inside partial view. 
    @using (Ajax.BeginForm("EditQuiz", "Quiz", FormMethod.Post,
                        new AjaxOptions
                        {
                            InsertionMode = InsertionMode.Replace,
                            HttpMethod = "POST",
                            UpdateTargetId = "formdiv"
                        }))
{
        @Html.ValidationSummary(true)
        @Html.AntiForgeryToken()
        <div>
            <fieldset>
            .
            .              
            <input type="submit"  class = "btn btn-primary" value="Save" />
            <button  class = "cancel" >Cancel </button>
            </fieldset>
        </div>
  }
Joel
  • 647
  • 2
  • 11
  • 22

1 Answers1

0

I'm curious if your cancel button is whats causing the submit by default. Try replacing your <button class="cancel"> with an Html helper. How about @Html.ActionLink("Cancel", "Index"). This is a link that has text Cancel and redirects to action Index.

ElliotSchmelliot
  • 7,322
  • 4
  • 41
  • 64
  • Well, that does work. Of course with ActionLink it actually redirects which I don't want, so I had to do Cancel and then $("#cancelbutton").on("click", function (event) { $("#formdiv").hide(); }); Seems kinda hacky. Is that really how it should be done? – Joel Aug 13 '13 at 03:49
  • 1
    Buttons can default to type="submit" if you dont specify a type. Try specifying on your button: type="button". – ElliotSchmelliot Aug 13 '13 at 03:58
  • well crap. That seems to be more what I'm looking for. I don't think I ever put the type attribute on buttons but I'll double-check. I did say "No doubt it's some ignorance on my part.":) Thanks Elliot – Joel Aug 13 '13 at 04:06
  • Ya putting type=button on a button seems a bit redundant, I don't blame you. No problem, good luck! – ElliotSchmelliot Aug 13 '13 at 04:13