Click here to Skip to main content
15,881,843 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I am quite new to asp.net mvc, I am trying to display a bootstrap modal after I save the data. but its not showing modal or the modal disappears in a blink.
please see my code

thanks for the help in advance.

What I have tried:

controller action:
C#
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddNew(ProductModel pm)
{
 
    if (ModelState.IsValid)
    {                
        int result = IProductRep.Add(pm);
        if (result <= 0)
        {

            return HttpNotFound();
        }
        else
        {
            ViewBag.Saved = "saved";
       
        }
    }
   
    return View();
}

view : (button is in the form with form method post)
HTML
<input type="submit" class="btn btn-primary float-right shadow" value="Save"  data-toggle="modal" data-target="#exampleModal">

Razor
@if (ViewBag.Saved != null)
{
    <div class="modal fade" id="exampleModal">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                    
                        <span>×</span>
                    
                </div>
                <div class="modal-body">
                    New product has been saved successfully.
                </div>
                <div class="modal-footer">
                    Close
                    Save changes
                </div>
            </div>
        </div>
    </div>
}
Posted
Updated 1-May-23 0:22am
v3

1 solution

Bootstrap modals don't magically appear on their own. They are shown when you trigger them, either by clicking an element in the current page, or via Javascript.

Modal · Bootstrap v4.6[^]

You need to add some script to your page to display the modal dialog when the document loads.
Razor
@section Scripts {
    @if (ViewBag.Saved != null)
    {
        <script>
        $(function(){
            $("#exampleModal").modal("show");
        });
        </script>
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900