This is a real mystery for me and the other developers who have looked at it. I have a jquery function and within the function I have an if statement. There is some code within the statement body that I want executed when the condition is true, but not executed when the condition is false. Pretty simple. However, the code within the body is being executed, EVEN when the condition is false. The variable in the condition is called delayExists (which is outside the function). I tested using a variable (called test) within the function and "forced" the condition to be true - ONLY in this scenario is the if statement working correctly. I've stepped through the code using Chrome Developer tools and can see when delayExists becomes true yet the condition appears to be ignored. I've tried to include the pertinent code below. Please let me know I need to provide more.
<!-- at model specifies the type of object the view expects -->
#model atdaem
<div class="tab-pane" id="tab_delays">
<div class="row">
<div class="col-xs-12">
#(Html.Kendo().Grid<atdlm>().Name("delays-grid").Columns(columns =>
{
columns.Bound(c => c.Id).HeaderTemplate(" ").Width(1).ClientTemplate("<span style=\"white-space:nowrap;\">" + "<button type=\"button\" class=\"btn btn-social-icon btn-linkedin\" " + "data-toggle=\"modal\" data-target=\"\\#delayAddModal\" data-guid=\"#=Id#\" data-name=\"#=LocationName#\" " +
"data-title=\"Edit Delay\" >" + "<i class=\"fa fa-edit\"></i></button>" + "</span>");
;
}).DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Type(HttpVerbs.Post)
.Action("ActualDelayList", "TrainActivity")
.Data("actualJobTaskId")))
.Events(events => events.DataBound("delaysDatabound")))
<div class="pull-right top-buffer">
<button type="button" class="btn bg-green" data-toggle="modal"
data-title="Add Delay"
data-target="#delayAddModal">
<i class="fa fa-plus-square"></i>
Add delay
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="delayAddModal" tabindex="-1" role="dialog" aria-labelledby="delayAddLabel">
<div class="modal-dialog" role="document">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<!-- This "x" button is for dismissing the modal -->
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="delayAddLabel">Add Delay</h4>
</div>
<div class="modal-body">
<form name="delay-form" id="delay-form">
#Html.HiddenFor(m => m.atdId, new { id = "atdId" })
#Html.HiddenFor(m => m.ajtId)
#*Original:*#
<div class="form-group">
<!-- Renders floating text ("Subdivision") above the select options -->
#Html.LabelFor(m => m.SubdivisionId, new { #class = "field-label always-visible" })
<!-- ID for select element -->
<!-- Renders select class="select" id="SubdivisionId" name="SubdivisionId"><option value="4429faa8-5ad4-4adf-adde-ec7cf88ed9e9" innerHTML "Caltrain"-->
#Html.DropDownListFor(m => m.SubdivisionId, Model.AvailableSubdivisions, new { #class = "select" })
#Html.ValidationMessageFor(m => m.SubdivisionId)
</div>
<div class="row">
<!--Start milepost -->
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.StartMilepost, new { #class = "field-label" })
#Html.TextBoxFor(m => m.StartMilepost, new { #class = "form-control", placeholder = Html.DisplayNameFor(m => m.StartMilepost) })
#Html.ValidationMessageFor(m => m.StartMilepost)
</div>
</div>
<!-- End milepost -->
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.EndMilepost, new { #class = "field-label" })
#Html.TextBoxFor(m => m.EndMilepost, new { #class = "form-control", placeholder = Html.DisplayNameFor(m => m.EndMilepost) })
#Html.ValidationMessageFor(m => m.EndMilepost)
</div>
</div>
</div>
<!-- Location -->
<div class="form-group">
#Html.LabelFor(m => m.LocationId, new { #class = "field-label always-visible" })
<select id="LocationId" name="LocationId" class="select">
#foreach (var loc in Model.AvailableLocations)
{
<option value="#loc.Id" data-milepost="#loc.Milepost">#loc.Name</option>
}
</select>
#Html.ValidationMessageFor(m => m.LocationId)
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<!-- call to js function-->
<button id="delayAddButton" type="button" class="btn btn-primary" data-title="Add Delay">Add Delay</button>
</div>
</div>
</div>
</div>
<script>
var delayExists = false;
//the jquery function is listening for the element with the id #delayAddModal (which is also used for delayEdit); when that modal is shown (by someone clicking
// on the Add Delay button which has a data-target that points to the modal), just before the modal appears this fuction executes)
$("#delayAddModal")
.on("show.bs.modal",
function(event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var modal = $(this);
var title = button.data('title'); // get New title from data-title attribute
var delId = button.data("guid");
var name = button.data("name");
var conditionalVariable = 1;
var updateButtonValue = "Save Edit";
modal.find('.modal-title').text(title); // set title to New title
modal.find('#delayAddButton').text(updateButtonValue); // set button value to Edit Delay
$.ajax({
type: "GET",
url: "/TrainActivity/GetDelayDataForEditing/" + "?delayId=" + delId,
dataType: 'json',
success: function(data) {
delayExists = true;
modal.find('');
var sub = data.SubdivisionId;
$.getJSON('/TrainActivity/LocationBySubdivisionList?id=' + sub,
function(locs) {
// the stuff that needs to happen before the parent ajax completes needs to go in here
$('select#SubdivisionId').val(data.SubdivisionId).trigger('change');
$('#StartMilepost').val(data.StartMilepost);
$('#EndMilepost').val(data.EndMilepost);
$('#LocationId').val(data.LocationId).trigger('change');
//$('select#LocationId').val(data.LocationId).trigger('change');
});
},
error: function() { alert("error in Delay Edit"); }
});
});
//matches location based on input in Start Milepost
$(document)
.ready(function() {
var test = true;
//matches location based on input in Start Milepost
var button = $(event.relatedTarget); // Button that triggered the modal
var delId = button.data("guid");
if (test == false) {
//if (delayExists == false) {
$("#StartMilepost").change(function() {
$("#EndMilepost").val($(this).val());
//nearestMilepost();
});
}
#*function nearestMilepost()
{
//var mile = parseFloat($(this).val());
var mile = $("##Html.IdFor(m => m.StartMilepost)").val();
var sub = ($("#SubdivisionId").val());
var locationId = $('#LocationId option').filter(function () {
return parseFloat($(this).data('milepost')) >= mile
}).val();
$("#LocationId").val(locationId).change();
}
});
//changing the subdivision changes the locations available in the location box
#*$("#SubdivisionId").change(function () {
var sub = $(this).val();
$.getJSON('#Url.Action("LocationBySubdivisionList", "TrainActivity")?id=' + sub,
function (locs) {
var list = $('##Html.IdFor(model => model.LocationId)');
list.find('option').remove();
$(locs).each(function (index, loc) {
list.append('<option value="' + loc.Id + '" data-milepost="'+ loc.Milepost+'">' + loc.Name + '</option>');
});
nearestMilepost();
});
});*#
});
</script>
The misunderstanding is here:
if (delayExists == false) {
$("#StartMilepost").change(function() {
$("#EndMilepost").val($(this).val());
// etc.
});
}
That check happens once, at startup. Is delayExists false? Yes (at startup), so we add that handler. Which will always run all of the code within.
If you want to check the flag everytime #StartMilepost changes, you need to do that:
$("#StartMilepost").change(function() {
if (delayExists == false) {
$("#EndMilepost").val($(this).val());
// etc.
}
});
Related
I have a div called project and it is rendered with EJS
There several projects in the data for EJS, they are rendered by forEach loop - so several similar div appear.
The project div has id for identification in Jquery.
Further it has a project.name and project.id as a data-*
The problem which I encountered:
If I don't reload the page as intended - first try works well and Element inner text get updated correctly.
But on second try to change another project name both are changed to value of previous, so to say for both projects. In few words - new change overrides all previous. How is it possible?
Link to see how it looks in GIF
Imgur
Strange behaviour of chaining requests Imgur
<%userData.forEach(function(project){%>
<div class="project" id='project <%=project.id%>'>
<div class="projectHeader">
<div class="projectTitle">
<h5 id="projectTitle <%=project.id%>" class="projectName">
<%=project.name%>
</h5>
<div class="projectButtons">
<span data-toggle="tooltip" data-placement="top" title="Edit Project Title">
<a data-toggle="modal" data-target="#editProjectTitleModal">
<i id="editProjectName" class="editProject fas fa-pencil-alt"
data-name="<%=project.name%>" data-id="<%=project.id%>"></i>
</a>
</span>
</div>
</div>
</div>
A simple modal is called when the a tag in project is clicked.
<div class="modal fade" id="editProjectTitleModal" tabindex="-1" aria-labelledby="exampleformModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form class="" action="" method="">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Title</h5>
</div>
<div class="modal-body">
<div class="input-group">
<input id="editProjectNameInput" autocomplete="off" pattern="[a-zA-Z0-9 ].{1,25}" title="1 to 25 characters" class="form-control" aria-label="With textarea" placeholder="Enter new title" required></input>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" id="confirmEditProjectName" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
Jquery event handler which serves to change project.name, at first sends it to database and ammend DOM with new name. So the database get the new data, but the page is not reloaded and project.name changed simultaneously.
It grabs project-name and project-id and sends Ajax regular post - method, on success - change element's inner text to project-name
// Edit Project Title by ID
$(document).on('click', "#editProjectName", function() {
//Grab Id of the Project
var editProjectId = $(this).attr('data-id');
//Fill Modal input with current project.name
var currentTitle = document.getElementById('projectTitle ' + editProjectId).innerText;
$("#editProjectNameInput").val(currentTitle)
var url = '/editProjectName';
$('#confirmEditProjectName').on('click', function(event) {
//Take new project name from updated modal input
var newTitle = $("#editProjectNameInput").val();
//If they are same - alert
if (currentTitle === newTitle) {
event.preventDefault();
alert("New Title should be different")
} else {
event.preventDefault();
if (newTitle.length > 1 && newTitle.length <= 25) {
$.ajax({
type: "POST",
url: url,
data: {
projectName: newTitle,
projectID: editProjectId
},
success: function(result) {
//Hide modal and change element inner text to new value
$("#editProjectTitleModal").modal('hide')
document.getElementById('projectTitle ' + editProjectId).innerText = newTitle;
},
error: function(err) {
console.log(err);
}
})
}
}
})
})
I removed the space from the IDs and I changed from using the ID of #editProjectName to just using the class that is already on that object of editProject.
<%userData.forEach(function(project){%>
<div class="project" id='project<%=project.id%>'>
<div class="projectHeader">
<div class="projectTitle">
<h5 id="projectTitle<%=project.id%>" class="projectName">
<%=project.name%>
</h5>
<div class="projectButtons">
<span data-toggle="tooltip" data-placement="top" title="Edit Project Title">
<a data-toggle="modal" data-target="#editProjectTitleModal">
<i class="editProject fas fa-pencil-alt"
data-name="<%=project.name%>" data-id="<%=project.id%>"></i>
</a>
</span>
</div>
</div>
</div>
// Edit Project Title by ID
$(document).on('click', ".editProject", function() {
//Grab Id of the Project
var editProjectId = $(this).attr('data-id');
//Fill Modal input with current project.name
var currentTitle = document.getElementById('projectTitle' + editProjectId).innerText;
$("#editProjectNameInput").val(currentTitle)
var url = '/editProjectName';
$('#confirmEditProjectName').on('click', function(event) {
//Take new project name from updated modal input
var newTitle = $("#editProjectNameInput").val();
//If they are same - alert
if (currentTitle === newTitle) {
event.preventDefault();
alert("New Title should be different")
} else {
event.preventDefault();
if (newTitle.length > 1 && newTitle.length <= 25) {
$.ajax({
type: "POST",
url: url,
data: {
projectName: newTitle,
projectID: editProjectId
},
success: function(result) {
//Hide modal and change element inner text to new value
$("#editProjectTitleModal").modal('hide')
document.getElementById('projectTitle' + editProjectId).innerText = newTitle;
},
error: function(err) {
console.log(err);
}
})
}
}
})
})
After some research I have found out that once the on('click') is called it is On until the page get reloaded.
Thanks to this Question and Answer:
https://stackoverflow.com/a/6121501/13541013
I figured out - on('click') event should be switched off by calling $(this).off() (this is the event)
In my case I had to make $(this).off() right after:
$(document).on('click', "#editProjectName", function() {
$(this).off() ... further code
And it has to be done for every single on('click') event in the script.
I'm creating a project in ASP.NET MVC and jQuery. When a user click on addSentence button, I want to duplicate a div called copythis with all events and insert it in another div called myform.
in copythis I have two div: in the first there is a span called sentence where I insert the text in the input in the second the user can add more then one field with different text.
When the user clicks the button called save I want to read all copythis in myform and create a structure to send to a webapi.
I have a problem is the javascript because I can read properly each div.
$("#addSentence").on("click", function (event) {
if ($("#inputSentence").val() == "")
alert("Sentence must have a value");
else {
event.preventDefault();
var theContainer = $("#copythis");
if (theContainer != null) {
var clonedSection = $(theContainer).clone(true);
if (clonedSection != null) {
$(clonedSection).find("#sentence")
.text($("#inputSentence").val());
$(clonedSection).appendTo("#myform");
}
}
}
});
$("#save").on("click", function (event) {
$("#myform #copythis").children().each(function (index, element) {
var elm = $(this);
var sentence = elm.find('.row span#sentence').val();
if (sentence != '') {
console.log('Sentence: ' + sentence);
$("input").children().each(function (m, l) {
var txt = $(this).val();
if (txt != '') {
console.log('Example: ' + txt);
}
});
}
});
});
function makeRepeater(sectionsSelector, addClass, removeClass, AYSMsg) {
$(sectionsSelector + " " + addClass + "," + sectionsSelector +
" " + removeClass).on("click", function (event) {
// Avoiding the link to do the default behavior.
event.preventDefault();
// Get the container to be removed/cloned
var theContainer = $(this).parents(sectionsSelector);
if ($(this).is(addClass)) {
// Cloning the container with events
var clonedSection = $(theContainer).clone(true);
// And appending it just after the current container
$(clonedSection).insertAfter(theContainer);
} else {
// If the user confirm the "Are You Sure" message
// we can remove the current container
if (confirm(AYSMsg)) {
// Making fade out, hide and remove element a sequence
// to provide a nice UX when removing element.
$(theContainer).fadeOut('normal',
function () {
$(this).hide('fast',
function () { $(this).remove(); }
);
}
);
}
}
});
}
makeRepeater(
'.my-repeated-section-form', /* The container selector */
'.addform', /* The add action selector */
'.removeform', /* The remove action selector */
'Are you sure you want to remove this section?' /* The AYS message. */
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="row">
<div class="row">
<div class="col-lg-10">
<div class="input-group">
<input id="inputSentence" type="text"
class="form-control" placeholder="Sentence...">
<span class="input-group-btn">
<button class="btn btn-secondary"
type="button" id="addSentence">Add</button>
</span>
</div>
</div>
</div>
<div class="col-lg-12">
<div style="display: inline;">
<div class="group-of-repeated-sections" style="display: none;">
<div class="my-repeated-section">
<div id="copythis">
<div class="row">
<div class="col-lg-10">
<span id="sentence"></span>
</div>
<div class="col-lg-2">
<span>
+
-
</span>
</div>
</div>
<div class="my-repeated-section-form">
<div class="row">
<div class="col-lg-12">
<input type="text" />
<span>
+
-
</span>
</div>
</div>
</div>
<div style="height:25px;"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="myform"></div>
<button id="save">Save</button>
I've replace my JS Confirm function with a bootstrap modal, this modal is async so I also had to change my code and add callbacks.
What I'm trying to is:
Pseudo Code
if `simApp["con1"]` then show first modal with 2 buttons
if return is clicked -> close modal.
if continue is clicked -> open second modal
if return is clicked -> close modal
if submit is clicked -> submit form (not included in code)
else open second modal
if return is clicked -> close modal
if submit is clicked -> submit form (not included in code)
This is all very simple when you don't use callbacks, which I'm fairly new to.
So this is what I did, its NOT working, I guess it has something to do with the generic use of the modal. - JSFIDDLE
HTML
<div class="modal fade" id="generalModalTwoButtons" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" id="btn-return" class="btn btn-primary" data-dismiss="modal"></button>
<button type="button" id="btn-submit" class="btn btn-primary" data-dismiss="modal"></button>
</div>
</div>
</div>
</div>
<button id="go">GO</button>
JS
simApp = {};
simApp["con1"] = true; //in this code I hard-coded the conditions to ture
simApp["arr"] = [1];
$("#go").click(function () {
if (simApp["con1"] && simApp["arr"].length < 5) {
var msg = '<p>msg1</p>';
updateGeneralTwoButtonsModal('#a94442', 'header1', msg, 'Return', 'Continue', function (result) {
if (result === true) {
confirmBeforeSubmit(submitFormApproved);
}
});
} else {
confirmBeforeSubmit(submitFormApproved)
}
});
function submitFormApproved(result) {
if (result === true) {
console.warn("submitted");
}
}
function confirmBeforeSubmit(callback) {
var msg = '<p>msg2</p>';
if (simApp["con1"]) msg = '<p>msg2-changed</p>';
updateGeneralTwoButtonsModal('#31708f', 'header2', msg, 'Return', 'Submit', callback);
}
function updateGeneralTwoButtonsModal(color, title, body, btnReturn, btnSubmit, callback) {
var confirm = $('#generalModalTwoButtons');
confirm.find('.modal-header').css('color', color);
confirm.find('.modal-title').text(title);
confirm.find('.modal-body').html(body);
confirm.modal('show');
confirm.find('#btn-return').html(btnReturn).off('click').click(function () {
confirm.modal('hide');
callback(false);
});
confirm.find('#btn-submit').html(btnSubmit).off('click').click(function () {
confirm.modal('hide');
callback(true);
});
}
Any idea what I did wrong?
P.S - for learning purposes I would like to avoid using promises on this solution.
Here you go, the main problem I found was the fact that you don't block the propagation of the click event which automatically closes the modals. I added the event handler stopPropagation in the event of the continue/submit button.
simApp = {};
simApp["con1"] = true;
simApp["arr"] = [1];
$("#go").click(function () {
if (simApp["con1"] && simApp["arr"].length < 5) {
var msg = '<p>msg1</p>';
updateGeneralTwoButtonsModal('#a94442', 'header1', msg, 'Return', 'Continue', function (result) {
if (result === true) {
confirmBeforeSubmit(submitFormApproved);
}
});
} else {
confirmBeforeSubmit(submitFormApproved)
}
});
function submitFormApproved(result) {
if (result === true) {
console.warn("submitted");
}
}
function confirmBeforeSubmit(callback) {
var msg = '<p>msg2</p>';
if (simApp["con1"]) msg = '<p>msg2-changed</p>';
updateGeneralTwoButtonsModal('#31708f', 'header2', msg, 'Return', 'Submit', callback);
}
function updateGeneralTwoButtonsModal(color, title, body, btnReturn, btnSubmit, callback) {
var confirm = $('#generalModalTwoButtons');
confirm.find('.modal-header').css('color', color);
confirm.find('.modal-title').text(title);
confirm.find('.modal-body').html(body);
confirm.modal('show')
confirm.find('#btn-return').html(btnReturn).off('click').click(function () {
confirm.modal('hide');
callback(false);
});
confirm.find('#btn-submit').html(btnSubmit).off('click').click(function (event) {
event.preventDefault();
event.stopPropagation();
if(btnSubmit != "Continue") {
confirm.modal('hide');
}
callback(true);
});
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<div class="modal fade" id="generalModalTwoButtons" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" id="btn-return" class="btn btn-primary" data-dismiss="modal"></button>
<button type="button" id="btn-submit" class="btn btn-primary" data-dismiss="modal"></button>
</div>
</div>
</div>
</div>
<button id="go">GO</button>
I have a modal form that save me on certain data information, work correctly, but I need to update a in my view with the response and doesn't work correctly and bring me a list without format and class css, like when an error occurs, the modal disappears and brings back a page without css with all the validates error, what I have wrong in my code or that I do to fix it?
My Partial View
#model ControlSystemData.Models.Tourist
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel-Update">Ingresar Turista</h4>
</div>
#using(#Html.BeginForm("Create","Tourist", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<div class="modal-body" style="text-align:center; padding:10px;">
#if (!string.IsNullOrWhiteSpace(ViewBag.Error))
{
<div class="alert alert-danger alert-dismissable" id="danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#ViewBag.Error
</div>
}
<div class="panel-body">
<div class="form-group">
#Html.TextBoxFor(u => u.Name, new { #class = "form-control", #placeholder = "Nombre del Pasajero" })
#Html.ValidationMessageFor(u => u.Name)
</div>
#*More Data Here*#
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Guardar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</fieldset>
}
My Modal Bootstrap
<!--Modal Tourist-->
<div class="modal fade" id="Modal-Tourist" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<p class="body">
</p>
</div>
</div>
</div>
<!--End Modal Tourist-->
My Controller
[HttpPost]
public ActionResult Create(Tourist collection)
{
if (ModelState.IsValid)
{
db.Tourist.Add(collection);
db.SaveChanges();
return RedirectToAction("IndexByEventsTourist", "Tourist", new { id = collection.id });
}
Response.StatusCode = 400;
return PartialView("Create", collection);
}
My Script
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
function clearErrors() {
$('#msgErrorNewTourist').html('');
$('#alert').html('');
}
function writeError(control, msg) {
var err_msg = '<div class="alert-message error"><a class="close" href="#">×</a><p>' + msg + '</p></div>';
$('#' + control).html(err_msg);
}
$(document).ready(function () {
$('#Modal-Tourist form').on('submit', function () {
if ($(this).valid()) {
$.ajax({
url: '#Url.Action("Create","Tourist")',
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
$("#eventsDetailsList").html(result);
},
error: function (err) {
writeError('body', 'Wrong Data');
}
});
}
return false;
});
function getRequest(url) {
jQuery.noConflict();
$.ajax({
url: url,
context: document.body,
success: function (data) {
$('.modal-content p.body').html(data);
$('#Modal-Tourist').modal('show');
$('#Name').focus();
},
error: function (err) {
writeError('msgErrorNewTourist', err.responseText);
}
});
}
$('a.newTourist').click(function () {
var id = $(this).attr("eventsid");
var url = '#Url.Content("~/Tourist/Create")/' + id;
getRequest(url);
return false;
});
});
</script>
I need that the modal stay in your position with your errors or rendering my correctly with the update.
Thanks
Images
RedirectToAction
public ActionResult IndexByEventsTourist(int id)
{
ViewBag.id = id;
var eventsById = db.Events.Where(u => u.id == id).FirstOrDefault();
ViewBag.Events = eventsById;
var touristByEvent = db.Tourist.Where(u => u.id == id).Include(u => u.Events).ToList();
ViewBag.TouristByEvent = touristByEvent;
return PartialView("IndexByEvents", touristByEvent);
}
Parent page (Render Div with the Partial Render or Update from Modal)
<div class="col-lg-8">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-plus"></i> Add
</div>
<div class="panel-body">
<div class="row">
<div id="msgErrorNewTourist"></div>
<div class="col-lg-12" id="eventsDetailsList">
#{Html.RenderAction("IndexByEventsTourist", "Tourist", new { id = Model.id });}
</div>
</div>
</div>
</div>
</div>
</div>
After many tries, I changed the <script></script> (my script it was very obsolete) and I modified the <script> of this answer for my intent of load content dynamically and Validate the form before Post, Many Thanks to Sthepen Muecke for provide me a solution and clarify my issues... Thank you so much.
New Code Script for Load Content Dinamically and Validate Inputs in Modal Bootstrap 3
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('a.newTourist').click(function () {
var url = '#Url.Action("Create", "Tourist", new { id = #Model.id })';
$(jQuery.noConflict);
$('#ModalContent').load(url, function (html) {
var form = $("#Modal-Tourist form");
$.validator.unobtrusive.parse(form);
$("#Modal-Tourist").modal('show');
form.submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
var content = '#Url.Action("IndexByEventsTourist", "Tourist", new { id = #Model.id })';
$('#eventsDetailsList').load(content);
}
});
return false;
});
});
});
});
</script>
I have an Index View and when I click the Edit button, I post to the Edit View (via the Controller) and display a bootstrap modal popup.
By posting to the Edit View, the Controller/View automatically handle getting and displaying the correct data on the modal popup.
Once I'm on my Edit View with the dialog box appearing and I click on the Close button, I simply want to link back to the Index page again; but instead, am getting an error with the path of the url. The new path I want to link to is being "tacked on" to the original path instead of replacing it.
I'm using the Url.Action method inside the click event of the Close button (of which I verified it's hitting) and have verified the location.href url is exactly what is in the url variable as you see in the code.
What do I need to do to correctly link back to the Index url?
Index View
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>Edit
Edit Controller
// GET: Categories/Edit/5
public async Task<ActionResult> Edit(short id)
{
if (id == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Category category = await db.GetCategoryIDAsync(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
Edit View
#model YeagerTechDB.Models.Category
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="modal" id="categoryEditModal" tabindex="-1" role="dialog" aria-labelledby="categoryModal-label" 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" id="categoryModal-label">Category Description</h4>
</div>
<div class="modal-body">
<div class="form-group">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CategoryDescription, new { #class = "control-label required col-offset-1 col-lg-3 col-md-3 col-sm-3 col-xs-3" })
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
#Html.EditorFor(model => model.CategoryDescription, new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.CategoryDescription, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" id="btnCloseCategory">Close</button>
<button type="submit" class="btn btn-primary" id="btnSaveCategory">Save</button>
</div>
</div>
</div>
</div>
<div>
#Html.Hidden("categoryEditUrl", Url.Action("Edit", "Category", new { area = "Categories" }))
#Html.Hidden("catID", Model.CategoryID)
</div>
#section Scripts {
<script>
$(document).ready(function ()
{
if (typeof contentEditCategory == "function")
contentEditCategory()
});
</script>
}
JS for Edit View
$('#btnCloseCategory').click(function (e)
{
var url = '#Url.Action("Index", "Category", new { area = "Categories" })';
location.href = url;
return false;
});
Image of modal popup
Image of error
Assuming your javascript is in an external file you could do the following:
Attach the url to your button within your view with a data attribute as follows:
<button type="submit" class="btn btn-default" id="btnCloseCategory"
data-url="#Url.Action("Index", "Category", new { area = "Categories" })">Close</button>
Then pull back the url with the data method as follows:
$('#btnCloseCategory').click(function (e)
{
var url = $(this).data('url');
location.href = url;
return false;
});
Try changing type="submit" to type="button" for your Close button.
<button type="button" class="btn btn-default" id="btnCloseCategory">Close</button>