سؤال

I am using Bootstrap2. The following is HTML markup in an ASP.NET MVC4 AJAX form -

@using (Ajax.BeginForm("ItemPost", "Supervisor", null, ajaxOptions, new { @id = "frmItem" }))
{
<button id="btnShowNewItemDiv" class="btn pull-right">
    <i class="sm-icon-cube"></i>&nbsp;<span id="newItemSpan">@Supervisor.IBtnNewItem</span>
</button>

<div id="NewItemDiv" style="display: none;">
    <h2 class="h2NewItem">@Supervisor.Ih2</h2>

    <div id="itemContent">
        <div class="alert alert-info fade in">
          <button class="close" data-dismiss="alert" formnovalidate>x</button>
             Some text here
        </div>
    </div>

I have intentionally omitted rest of code to make code short.

Problem

On click of dismiss button in bootstrap alert, it is performing ajax call and submitting form. How do I avoid this behavior?

هل كانت مفيدة؟

المحلول 3

Both comments from @Verkion and @Matt are sufficient to resolve this issue. But not in context with Bootstrap.

Because my earlier MVC4 + Bootstrap applications were/are working fine with same conditions. I investigate further what could be the real cause?

Finally I found a stupid solution. The solution was to include bootstrap-alert script file ("~/Content/bootstrap/js/bootstrap-alert.js") in ajax page.

نصائح أخرى

instead of using an ajax.beginform put your ajax call into a button click event

$('#btnShowNewItemDiv').on('click', function(){
    if ($('form').valid()) {
        $.ajax({
            url: '@Url.Action("Action", "Controller")',
            type: 'POST',
            cache: false,
            async: true,
            data: $('form').serialize(),
            success: function(result){
                //do something with the result
            }
        });
    }
});

This is because the default behavior of the button is to trigger the POST. Try this, to stop the default behavior:

$(function() {
  // wire up close button click event
  $("#itemContent button").click(function(e) {
     e.preventDefault(); // cancel default behavior
     var alert = $(this).closest('.alert'); 
     $(alert).alert('close'); // close the alert
  });
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top