I have two buttons in a view that call different modal windows ("AgregarProducto") and ("CargarOrden")
Cargar O. de Compra <span class="glyphicon glyphicon-file" aria-hidden="true"></span>
Agregar Producto <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
These are loaded using the following Javascript code:
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", "a.dialog-window", null, function (e) {
e.preventDefault();
var $link = $(this);
var title = $link.text();
$('#AgregarProducto.modal-title').html(title);
var url = $(this).attr('href');
if (url.indexOf('#') == 0) {
$('#AgregarProducto').modal('show');
}
else {
$.get(url, function (data) {
$('#AgregarProducto .te').html(data);
$('#AgregarProducto').modal();
}).success(function () { $('input:text:visible:first').focus(); });
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", "a.dialog-window", null, function (e) {
e.preventDefault();
var $link = $(this);
var title = $link.text();
$('#CargarOrden.modal-title').html(title);
var url = $(this).attr('href');
if (url.indexOf('#') == 0) {
$('#CargarOrden').modal('show');
}
else {
$.get(url, function (data) {
$('#CargarOrden .te').html(data);
$('#CargarOrden').modal();
}).success(function () { $('input:text:visible:first').focus(); });
}
});
});
</script>
}
The problem is that clicking on a button loads the window twice! (I attach a photo)
in my controllers I made sure to call a partial type view
[HttpGet]
public ActionResult AgregarProducto()
{
return PartialView();
}
[HttpGet]
public ActionResult CargarOrden()
{
return PartialView();
}
I'm using bootstrap to call my views "AddProduct" and "LoadOrder" from my main view ... my two containers:
div class="modal fade" id="AgregarProducto" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class="modal-title"></h2>
</div>
<div class="modal-body"><div class="te">Espere Porfavor...</div></div>
</div>
</div>
</div>
<div class="modal fade" id="CargarOrden" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class="modal-title"></h2>
</div>
<div class="modal-body"><div class="te">Espere Porfavor...</div></div>
</div>
</div>
</div>
I have never worked with modal windows, what happens? what am I doing wrong? any help for me?
You have 2 scripts, one which opens the AgregarProducto modal, and the one which opens the CargarOrden modal.
Because both scripts are executed when ever you click on a link with class="dialog-window", (which both your links have), then both scripts are executed, and both modals are displayed.
A simple solution is to just give your links an id attribute, say id="cargarorden" for the first link and id="agregarproduct" for the second, then change the scripts to
$('#cargarorden').click(function(e) {
.... // you code that opens the CargarOrden modal
});
$('#agregarproduct').click(function(e) {
.... // you code that opens the AgregarProducto modal
});
Note that since the links are not loaded dynamically, then there is no need to use event delegation using .on().
A better alternative would be to identify the associated modal in the link using a data- attribute so that only one script is required
<a data-dialog="CargarOrden" href="#Url.Action("CargarOrden", "Entradas")" ...>
and then
$('.dialog-window').click(function(e) {
// Get the associated dialog
var dialog = $('#' + $(this).data('dialog'));
....
});
and within that script, use dialog as your selector, i.e.
dialog.find('.modal-title').html(title); // instead of
dialog.modal('show'); // instead of $('#CargarOrden').modal('show');
dialog.find('.te').html(data); // instead of $('#CargarOrden .te').html(data);
Related
When I make an ajax call, I show my modal (options.beforeSend). But, when I get an ajax result error (options.error) I would like to hide this modal. I've tryied but no success.
Index.cshtml
#* Modal - load spin *#
<div class="modal fade" id="itemLoader" tabindex="-1" role="dialog" aria-labelledby="ModalLabel2" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"></h5>
</div>
<div class="modal-body d-inline text-center">
<div class="spinner-border spinner-border-sm text-info" role="status">
<span class="sr-only small"></span>
</div>
<span class="far fa-dizzy fa-3x text-secondary" style="display:none;"></span>
<label id="ModalStatus">Loading...</label>
</div>
</div>
</div>
</div>
Before send I toggle/show the modal:
options.beforeSend = function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
// My modal (works fine)
$('#itemLoader').modal('toggle');
$('#itemLoader').modal('show');
};
options.success = function (data) {
if (data.idOrder!= null) {
window.location.href = "/app/order/order?Id=" + data.idOrder;
}
};
If error (after a partial view return, from ModelState is not valid), I am trying to hide the modal, but I can't:
options.error = function (res) {
// When my modelState is not valid, return partial view with required messages (working fine)
$('#chkForm').html(res.responseText);
// But I can't hide the modal (does not work)
var modal = $("#itemLoader");
modal.hide();
// hide modal (does not work)
$('#itemLoader').modal('hide');
$('#itemLoader').hide();
};
I have tryied the close button on modal, but no sucess as well:
<button id="btnclosemodal" class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
// Does not work
$('#btnclosemodal').click();
// Does not work
$("#btnclosemodal").trigger("click");
error function will be called if the request fails. I think here it will not enter the error function since it return the partial view normally. You can use f12 and debug it in the source tab.
Instead, I think you should hide the modal in the success function.
You can try to toggle the modal on error, like this:
$('#itemLoader').modal('toggle');
I have ActionResult method that uses Httpost, but when I debug it does not get in the method, only ends in ActionResult for using HttpGet. What could be the main reason for this? I want to store value back to the database column, at this point it does non of that and have debug as well inspect nothing on the browser.
//GET/Courses-List
[HttpGet]
public ActionResult CoursesRegistration()
{
eNtsaCourses courses = new eNtsaCourses();
//courses.Course = Course;
return View();
}
[Route("Home/CoursesRegistration")]
[HttpPost]
public ActionResult CoursesRegistration([Bind(Include = "Id,Course,Nickname,Term, EnrolledAs, Published")] eNtsaCourses courses)
{
if(ModelState.IsValid)
{
try
{
cb.eNtsaCourse.Add(courses);
cb.SaveChanges();
return Json(new { success = true });
}
catch(Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
}
return PartialView("CoursesRegistration", courses);
}
#using(Html.BeginForm("CoursesRegistration", "Home", FormMethod.Post, new { id="testForm", #class="form-horizontal"})) {
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Start New Course</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="form-group row">
<label for="CourseName" class="col-sm-3 col-form-label">CourseName</label>
<div class="col-sm-5">
#Html.EditorFor(model => model.CourseName, new { htmlAttributes = new { #class = "form-control", autofocus = "autofocus", placeholder = "CourseName" } })
</div>
</div>
<div class="form-group row">
<label for="Content-Licence" class="col-sm-3 col-form-label">Content Licence</label>
<div class="col-sm-5">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
Create Courses
<script type="text/javascript">
$("#exampleModal.btn-success").click(function () {
saveData();
});
function saveData() {
$.ajax({
url: "/Home/CoursesRegistration",
data: $('#testForm').serialize(),
type: 'post',
success: function (data) {
if (data.Success) {
$("#exampleModal").modal('hide');
} else {
}
},
error: function (xhr, status) {
}
});
return false;
}
</script>
</div>
</div>
}
ok a couple of things, why in razor are you using a Html.BeginForm and then overriding that with ajax/js?
Best bet here would be choose one method and use that, my preference would be sticking the whole modal into a partial and using a C# object as the model for that partial, then you can use your beginform without having to mess around with ajax/js and serialisation.
Then you can have a single input of the model in your controller POST function.
Have you checked to see if the button is actually firing the js? I noticed you wired it up to
$("#exampleModal.btn-success").click(function () {
saveData();
});
when it should be
$("#exampleModal .btn-success").click(function () {
saveData();
});
maybe stick some console logs in to check and see if it fires and what the data is prior to sending.
Also change the controller function to a httpget to see if it is finding the route ok, then change back to post and you should know then if it is the controller, the route, or the frontend code. I suspect the frontend code.
$(selector).click(function);
If you are using multiple selector in jquery then take a space between two selector.
You need to use as below
$("#exampleModal .btn-success").click(function () {
saveData();
});
I would like to have this error modal window appear if there are issues or errors that need to be displayed to the user after calling the SaveDailyCriteria action. I need the partial view to be rendered within the view where the SaveDailyCriteria action call is made. With the code that I currently have below, the return PartialView("_ErrorsModal", notification) gets called but is never displayed on my main view.
Controller
[HttpPost]
public ActionResult SaveDailyCriteria(Daily report, string EnteredCriteriaName)
{
var criteria = report.ConvertToCriteria(report);
criteria.CriteriaName = EnteredCriteriaName;
var dr = new ReportDaily();
var nameExists = dr.DoesCriteriaNameAlreadyExist(criteria);
if (dr.SaveReportCriteria(criteria, nameExists, out Notification notification) == false)
{
return PartialView("_ErrorsModal", notification);
}
else {
return View(report);
}
}
Main View
#model Company.Areas.Reports.Models.Daily
#using Company.TaxCollection.Reports;
#{
ViewData["Title"] = "Daily Report";
}
<h1>#ViewData["Title"]</h1>
<br />
#using (Html.BeginForm("DailySubmit", "Reports", FormMethod.Post, new { id = "reportForm", #class = "report-form col-9" }))
{
...
...
<div id="saveModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title float-left">Save Criteria</h4>
<button type="button" class="close" data-dismiss="modal"></button>
</div>
<div class="modal-body">
<label>Enter the name to save as:</label><input type="text" id="savedReportName" name="EnteredCriteriaName" class="form-control" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="saveSubmit" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
}
<script>
$(document).ready(function () {
var dataType = 'application/x-www-form-urlencoded; charset=utf-8';
$(function () {
$('#saveSubmit').on('click', function (evt) {
var data = $('form').serialize();
//Ajax form post
$.ajax({
type: 'POST',
data: data,
contentType: dataType,
url: '#Url.Action("SaveDailyCriteria", "Reports")',
success: function (data) {
console.log(data);
if (data.success) {
//window.location.href = data;
} else {
//window.location.href = data;
}
}
});
});
});
});
</script>
_ErrorsModal Partial View
#model Company.NotificationPattern.Notification
<!-- Modal -->
<div id="errorsModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title float-left">Warning</h4>
<button type="button" class="close" data-dismiss="modal"></button>
</div>
<div class="modal-body">
#if (Model.HasErrors || Model.HasWarnings) {
<p>#Model.GetConcatenatedErrorMessage(Environment.NewLine + Environment.NewLine)</p>
}
</div>
<div class="modal-footer">
<button type="button" id="modalConfirm" class="btn btn-primary" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
You can achieve this various ways, one option:
In your controller post method, return a json when it passes and the partial when it fails.
Within your jquery $.ajax post check for json and proceed otherwise render the result to your modal
In your case, the json returned on pass would indicate the url of the view to redirect to (not the view itself otherwise there's no way to know if it's a new view or the partial error). e.g
if (save() == false)
{
return PartialView("_ErrorsModal", notification);
}
else {
return Json({
success = true,
url = this.Url.Action("SaveDailyCriteria", new { reportId = report.ReportId }
});
}
and your javascript to:
$.ajax({
type: 'POST',
...
success: function (data) {
if (data.success)
window.location.href = data.url;
else
$("#modalId").html(data);
}
});
the alternative is to always return json but render the _ErrorsModal (on error) or View (on success) within the controller to a string and add that string as a json property. IMO better to let the MVC pipeline handle rendering to HTML so recommend the above approach.
I am trying to create a partial view that will appear in a modal when a button gets pressed. If there is another approach that works better for this, I am open for it -- I had the modal working great until I added the List to the main view. If there is a way to return back a list and form post a single entity that might work for my scenario. Right now the code I have works to an extent, however you need to push the Add Service button twice in order for the modal to show up and when it does the only way to get rid of it is to submit, both the X in the top as well as the close button don't work.
main view
#model List<ServicesPosting>
<div>
<button id="addService" onclick="OpenModal()">Add Service</button>
</div>
<div id="AddServiceForm"></div>
<script type="text/javascript">
function OpenModal() {
var url = '#Url.Action("AddServiceModal", "Services")';
$('#AddServiceForm').load(url);
$('#serviceModal').modal();
}
</script>
controller
public class ServicesController : Controller
{
// GET: Services
public ActionResult Index()
{
List<ServicesPosting> postings = DataAccess.GetAllPostings();
return View(postings);
}
[HttpGet]
public ActionResult AddServiceModal()
{
return PartialView("~/Views/Services/AddNewService.cshtml");
}
}
partial view
#model ServicesPosting
<!-- Modal -->
<div class="modal fade" id="serviceModal" tabindex="-1" role="dialog" aria-labelledby="serviceModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<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" id="serviceModalLabel">Add New Service</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("Index", "Services"))
{
// TODO: validate up front
<div class="row">
Service Title : #Html.TextBoxFor(x => x.ServiceTitle)
</div>
<div class="row">
ServiceDescription : #Html.TextAreaFor(x => x.ServiceDescription)
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save Changes</button>
</div>
}
</div>
</div>
</div>
</div>
The problem is when you click the button first time the
$('#serviceModal').modal(); function is being called before the modal load.
So, you need to call this $('#serviceModal').modal(); function after $('#AddServiceForm').load(url); is done. Means that ater loading the AddNewService.cshtml is completed then you can find your desired modal in you DOM. See for more in here http://api.jquery.com/load/
After that you can show the modal. Some times when you add any DOM elements achieved by ajax call added to you main DOM specially DOM with form elements; the DOM parser can't get it first time so use the body tag to find any child element. I have put a code bellow. Try with this :
$("#AddServiceForm").load(url, function(responseTxt, statusTxt, xhr) {
// debugger;
if (statusTxt == "success")
{
$('body #serviceModal').modal('show');
}
if (statusTxt == "error")
{
console.log("Error: " + xhr.status + ": " + xhr.statusText);
}
});
I'm creating a modal using twitter bootstrap in my application.creating a modal on onclick event
It is working fine in firefox and chrome. but while running my application in ie8, inside that modal NewPage.aspx page is not getting viewed properly.
here is my code :
<div id="MyModal" class="modal hide in">
<div class="modal-dialog">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×</button>
<h3 id="myModalLabel">
Header</h3>
</div>
<div class="modal-content">
<div class="modal-body">
<iframe id="modal-frame" src="" style="zoom: 0.60; position: relative;" frameborder="0"
height="450" width="850"></iframe>
</div>
</div>
</div>
</div>
<button modalurl="~/NewPage.aspx" id="lnkNewModal" onclick="openMyModal(this);"
runat="server">Modal</Button>
function openMyModal(curObj) {
$("#MyModal").modal({
"backdrop": "static",
"keyboard": true,
"show": true
});
var url = $(curObj).data("modalurl");
$('#MyModal').on('show', function () {
$('#modal-frame').attr("src", url);
});
$('#MyModal').modal({ show: true });
}
Thank you all in advance for your response.
You have a slight error in the Javascript code
function openMyModal(curObj) {
var url = $(curObj).attr("modalurl"); //Note here
$('#MyModal').on('show', function () {
$('#modal-frame').attr("src", url);
});
$("#MyModal").modal({
"backdrop": "static",
"keyboard": true,
"show": true
});
}
this works perfectly , Cheers!!!