Bootstrap Modal will not load. It should load as soon as the View is rendered.
I've used this method of adding javascript through a section decleration to load a modal form in the same project. So, I know the jquery and bootstrap libraries that are included in the master pages are compatible. I just cannot figure out why this time around, the modal is not loading.
Browser console is not complaining about anything
My View
#using CaptchaMvc.HtmlHelpers
#{
ViewBag.Title = "Report Post";
}
<div class="modal fade" id="ReportReasonModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-notify modal-warning" role="document">
<div class="modal-content">
<div class="modal-header text-center" style="background-color:saddlebrown; color:white;">
<h4 class="modal-title white-text w-100 font-weight-bold py-2">Report Posting</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="post" action="/Items/Process Report">
<div class="modal-body">
#Html.ValidationSummary("", new { #class = "text-danger" })
</div>
<div class="modal-footer">
#* #Html.Captcha("Refresh", "Please Enter Captcha Value Below", 7, "Is required field.", false)*#
<button value="submit" type="submit" class="btn btn-outline-danger">Submit</button>
</div>
</form>
</div>
</div>
</div>
#section scripts
{
<script>
$(function () {
$("ReportReasonModal").modal();
alert("here")
});
</script>
}
Order of javascript loaded: excerpt from rendered masterpage with the scripts section rendered
<!-- jQuery library -->
<script src="/Scripts/jquery-3.3.1.js"></script>
<!-- Popper -->
<script src="/Scripts/umd/popper.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery-ui-1.12.1.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/mdb/mdb.js"></script>
<script>
$(function () {
$("ReportReasonModal").modal();
alert("here")
});
</script>
The modal should appear as soon as the view is rendered
You are not using the correct jQuery selector. The # is missing, to select an element with the id of ReportReasonModal. What you are currently trying to do is select an element of type <ReportReasonModal />
$("#ReportReasonModal").modal();
Related
I want to pop up my div class that contains user at password text box but nothings happen and I test also my function if its running correctly that's why I put alert in my function. This my code bellow. I try so many solution and yet still not show my div. Can any give me a best solution regarding this matter or other way to pop up the web form without leaving my current page.
#model TBSWebApp.Models.User
#{
ViewBag.Title = "UserLogin";
Layout = "~/Layout/_webLayout.cshtml";
}
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<div>
<fieldset>
<div class="container">
<div class="row">
<div class="col-xs-12">
<button id="btnShowModal" type="button" class="btn btn-sm btn-default pull-left col-lg-11 button button4">
Sign-in
</button>
<div class="modal fade" tabindex="-1" id="loginModal" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">Satya Login</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<input class="form-control" type="text" placeholder="Login Username" id="inputUserName" />
</div>
<div class="form-group">
<input class="form-control" placeholder="Login Password" type="password" id="inputPassword" />
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Sign</button>
<button type="button" id="btnHideModal" class="btn btn-primary button button4">
Hide
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</fieldset>
</div>
<footer>
<p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">
©
<script>document.write(new Date().toDateString());</script>
</p>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
//$(document).ready(function () {
$("#btnShowModal").click(function () {
alert("test");
$("#loginModal").modal('show');
});
$("#btnHideModal").click(function () {
$("#loginModal").modal('hide');
});
// });
</script>
I already solved my problem
<script>
$(document).ready(function () {
$("#submitButton").click(function () {
if (($("#userNameTextBox").val() != "") && ($("#passwordTextBox").val() != ""))
$.ajax(
{
type: "POST", //HTTP POST Method
url: "UserLogin/UserLogin", // Controller/View
dataType: "text/html",
data:
{ //Passing data
UserID: $("#userNameTextBox").val(),
Password: $("#passwordTextBox").val(),
}
});
});
});
//$(document).ajaxStart(function () { $("#loadingImg").show(); });
//$(document).ajaxStop(function () { $("#loadingImg").hide(); });
</script>
Can please someone help me here?! Thank you!
I have a view that displays a list of products along with an "Add Product" button for each. I am calling the CreateNewProduct method for each "Add Product" click to find the status of the product. Depending on the status, either I need to stay on the same view or I need to call a modal popup. I am able to do this by creating a modal popup in a different view. But I want to call the modal popup div (also pass the modal) from the same view where it displays a list of products. Is this possible?
public ActionResult CreateNewProduct(int productId)
{
var sharedProduct = _productTemplateService.GetSharedProducts(productId);
var _finalSharedProducts = (sharedProduct.Any(t => t.productId != productId));
if (_finalSharedProducts)
{
var sharedProdctTemplate = _productTemplateService.GetSharedProduct(productId);
return View("ModalView", new SharedModel
{
SharedProduct = sharedProdctTemplate
});
}
else
{
_productTemplateService.CreateNewProduct(productId);
return RedirectToAction("Details", "ProductTemplate");
}
}
Model View Code
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Shared Product</h4>
</div>
<div class="modal-body">
<div class="flex-row">
<div class="col-6">
<div class="d-flex flex-row">
<div class="p-2">Product ID</div>
<div class="p-2">Product Types</div>
<div class="p-2">Status</div>
</div>
#foreach (var productTemplate in Model.SharedProduct )
{
<div class="d-flex flex-row">
<div class="p-2">#productTemplate.ProductId</div>
<div class="p-2">#productTemplate.ProductType</div>
<div class="p-2">#productTemplate.StatusCode</div>
</div>
}
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
#Html.ActionLink("Back to List", "Index")
</p>
<script type="text/javascript">
$(document).ready(function () {
$('#myModal').modal('show');
});
</script>
UPDATE:
I made it working. This is what I did. At the end, I have mentioned issues I am facing.
Link, modal and script in my main view - Detail View (called from ProductTemplate Controller)
<td>Add New Product</td>
<div class="modal fade" id="mymodel" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Shared Products</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="mymodelbody">
</div>
</div>
</div>
<script>
var loadModal = function (productId, customerId) {
$.ajax({
type: 'GET',
url: '/NewProductTemplate/CreateNewProduct',
cache: false,
data: {
productId: productId,
customerId: customerId
},
dataType: 'html',
success: function (data) {;
$("#mymodelbody").html(data);
$("#mymodel").modal("show");
}
});
}
</script>
NewProductTemplateController Code
public ActionResult CreateNewProduct(Guid productId, Guid customerId)
{
var sharedProduct = _productTemplateService.GetSharedProducts(productId);
var _finalSharedProducts = (sharedProduct.Any(t => t.productId != productId));
if (_finalSharedProducts)
{
var sharedProdctTemplate = _productTemplateService.GetSharedProduct(productId);
return PartialView("_shared", new SharedModel
{
SharedProduct = sharedProdctTemplate
});
}
else
{
_productTemplateService.CreateNewProduct(productId);
return RedirectToAction("Details", "ProductTemplate");
}
}
Partial view _shared.view code
#model SharedModel
#using (Html.BeginForm("ShareProduct", "NewProductTemplate", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="flex-row">
<div class="col-6">
<div class="d-flex flex-row">
<div class="p-2">Product ID</div>
<div class="p-2">Product Types</div>
<div class="p-2">Status</div>
</div>
#for (var i = 0; i < Model.SharedProducts.Count(); i++)
{
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).ProductId)
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).CustomerId)
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).ProductType)
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).StatusCode)
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).IsShared)
<div class="d-flex flex-row">
<div class="p-2">#Html.DisplayFor(model => model.SharedProducts.ElementAt(i).ProductId)</div>
<div class="p-2">#Html.DisplayFor(model => model.SharedProducts.ElementAt(i).ProductType)</div>
<div class="p-2">#Html.DisplayFor(model => model.SharedProducts.ElementAt(i).StatusCode)</div>
#if (Model.SharedProducts.ElementAt(i).StatusCode == VersionStatus.PUBLISHED)
{
<div class="p-2">#Html.EditorFor(m => m.SharedProducts.ElementAt(i).IsShared)</div>
}
</div>
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-sm btn-primary" />
<button type="button" class="btn btn-sm btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
PROBLEM:
1) When I save submit button in modal pop-up (partial view), it calls ShareProduct method from NewProductTemplate controller. For some reason, model SharedModel's SharedProducts property is null when it gets to controller code. Can you please help me here why it gets null?
public ActionResult ShareProduct (SharedModel shareModel)
{
//Access ShareProducts from shareModel
return RedirectToAction("Details", "ProductTemplate");
}
PROBLEM:
2) I want to load popup only if the product is shared, otherwise I just want to redirect to Detail view as mentioned in NewProductTemplate controller's CreateNewProduct method. Problem is that it loads Detail view also in popup if product is not shared since that's what my script is doing. Is there any way that I can check data in Success function before showing modal popup? If data/html contains Shared text, I would like to load the normal Detail view. I am just assuming. I tried to do so but with no success.
Detail method in ProductTemplate Controller
public ActionResult Details()
{
var productTemplate = _productTemplateService.GetAllProducts(User);
return View(new DetailsModel
{
ProductTemplate = productTemplate,
});
}
(This is for Bootstrap 3.3.7 Hopefully it's relevant for the version you're on)
I handle this by popping open the modal on the client side from my main view. The link that pops the modal contains the URL to the controller method that will render the actual contents (list of products, in your case). This controller method should return a partial view.
Modal in my main view:
<div class="modal fade name-of-my-modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content"></div>
</div>
</div>
Link in my main view:
<a class="btn btn-default btn-xs" data-toggle="modal" data-target=".name-of-my-modal" role="button" href="/SomeController/SomeMethodThatReturnsPartialView/234">Show Modal</a>
My controller method for the partial view:
public ActionResult SomeMethodThatReturnsPartialView(int id)
{
var model = GetProducts();
return PartialView("_IndexPartial", model);
}
My partial view that will populate the actual modal contents:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Title goes here</h4>
</div>
<form class="form-horizontal" id="SomeId" name="SomeName" role="form">
<div class="modal-body">
<div>Product 1</div>
<div>Product 2</div>
<div>Product 3</div>
<div>Product 4</div>
</div>
</form>
Also, if the contents of the modal change frequently, or are variable based upon the ID you pass to the partial controller method, then you'll want to clear the modal contents when closing it. From your main view:
$(document).on('hidden.bs.modal', '.modal', function (e) {
// Handles the event thrown when a modal is hidden
$(this).removeData('bs.modal');
$(this).find(".modal-content").empty();
});
Let me know if this helps, and whether anything needs to be clarified.
Problem 2 you could return a JSON result and put the HTML in a string as shown here:
https://www.codemag.com/article/1312081/Rendering-ASP.NET-MVC-Razor-Views-to-String
you could also set a boolean on the returned JSON for whether to redirect.
If it is a redirect do that in Javascript on the success using
window.location
I have this code in my action
var singedUser = HttpContext.User.Identity.Name;
try
{
_purchaseService.PurchaseCard(singedUser, cardName);
}
catch
{
}
And I want this to open ONLY if the code enters the catch block
<div id="Modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Purchasing Card</h4>
</div>
<div class="modal-body">
<p>You have unsufficient funds!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
And here is my button
<a class="button btn btn-success"
asp-controller="Store" asp-action="Buy"
asp-route-data ="#card.Name">Buy (#card.Price coins)</a>
I would appreciate if someone would tell me how I can open this dialogue box in the same page only if the code enters the catch block
You can also use an ajax call to return the partial view and add it to the DOM. Setting up a modal to load a partial view is actually pretty straight forward :
Create partial view : _ModalContent.cshtml
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Purchasing Card</h4>
</div>
<div class="modal-body">
<p>You have unsufficient funds!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
Modify your Index page :
<a id="button1" class="button btn btn-success"
asp-controller="Store" asp-action="Buy"
asp-route-data ="#card.Name">Buy (#card.Price coins)</a>
<div id="myModal"></div>
#section Scripts{
<script type="text/javascript">
$(function () {
$.ajaxSetup({ cache: false });
$("#button1").on("click", function (e) {
$('#myModal').load(this.href, function () {
$('#Modal').modal({
keyboard: true
}, 'show');
});
return false;
});
});
</script>
}
Controller function :
public IActionResult buy(string data)
{
.....
{
return PartialView("_ModalContent");
}
}
I would pass a variable through the ViewBag on the controller/action. Something like this in the controller:
var singedUser = HttpContext.User.Identity.Name;
try
{
_purchaseService.PurchaseCard(singedUser, cardName);
}
catch
{
ViewBag.ShowModal = false;
}
Then toggle whether or not to trigger JQuery to show the Modal in the scripts section of the view:
#section Scripts{
<script>
#if(ViewBag.ShowModal == true){
#Html.Raw("$('#Modal').modal('show');");
}
</script>
}
I have input form in Bootstrap model popup. I want to show error message in div when submit button for saving. My model popup is in update panel. I am trying to do and its not working.
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">SMTP Configuration</h4>
</div>
<div class="modal-body">
Here is a input form
<div id="ErrorDiv" class="required" runat="server">
This is a div where i want to show content
</div>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Close</button>
<asp:Button ID="btnEdit" runat="server" Text="Save" OnClick="Save" class="btn btn-success" ValidationGroup="Group1" />
</div>
</div>
</div>
</div>
Below is the server side method to show content.
public void ShowError(string Message)
{
ErrorDiv.InnerHtml = Message;
upModal.Update();
}
How can I show error content to div?
To open error model popup from Server side.
You need to update your Server side function ShowError to this.
public void ShowError(string Message)
{
ErrorDiv.InnerHtml = Message;
upModal.Update();
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ErrorModel", "$('#myModal').modal('show');", true);
}
for this you have to put the div with id myModal, into update panel.
This will trigger jQuery function on Client side after server side execution complete and the model open manually.
Other way to do this
If you don't want to put model div into update panel then follow this way.
Update your Model div like below
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">SMTP Configuration</h4>
</div>
<div class="modal-body">
Here is a input form
<div id="ErrorDiv" class="required">
This is a div where i want to show content
</div>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Close</button>
</div>
</div>
</div>
</div>
Add JavaScript function as below into aspx file.
function showError(error){
$("#ErrorDiv").html(error);
$('#myModal').modal('show');
}
And call the JavaScript function from server side like this
public void ShowError(string Message)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ErrorModel", "ShowError('"+Message+"');", true);
}
Here, you can explore more about ScriptManager.RegisterStartupScript Method
I'm currently building a webapp in MVC C#. I want to open a popup window, where the user can enter lots of information, so he can make a new 'user'. However I have trouble making the window actually pop up. Later on, I'd also like to close the window, though I doubt that'll be much trouble after I got this. Below is my code so far:
<button class='btn btn-lg btn-default giveMeSomeSpace leaveMeAlone createUser dialog' onclick='createNewApplication()'>Create a new application</button>
<div class="modal" id="modal-new-app" tabindex="-1" role="dialog" aria-labelledby="modal-new-app" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
...
<div class="modal-body">
</div>
</div>
</div>
</div>
...
function createNewApplication() {
$.ajax({
url: '#Html.Raw(#Url.Action("Create", "User"))',
success: function (data) {
$("#modal-body").html(data);
},
cache: false
});
$('#modal-new-app').modal('show');
}
EDIT: corrected a typo, though that wasn't the error. Additionally, the error I get in Console of Chrome dev tools:
Uncaught TypeError: undefined is not a function
referring to
$('#modal-new-app').modal('show');
My and my college have been looking and we got it working.
<div class="modal" id="modal-new-app" tabindex="-1" role="dialog" aria-labelledby="modal-new-app" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close cancel" data-dismiss="modal"><span aria-hidden="true">×</span>
<span class="sr-only">Close</span></button>
<h4 class="modal-title">Create a new user</h4>
</div>
<div class="modal-body">
</div>
</div>
</div>
</div>
.
$(document).ready(function () {
createNewApplication();
$('#tableApps').DataTable();
});
function createNewApplication() {
$.get('#Html.Raw(#Url.Action("Create", "UserIS"))', function (data) {
$('#modal-new-app .modal-body').html(data);
});
}