I asked a question here yesterday about this issue but got downvoted, probably because I didn't include any code which is understandable.
Hopefully this question will be more complete and allow you to help me more easily.
So I have 3 views in play:
StudentsList
Script
#{
ViewBag.Title = "StudentsList";
Layout = "~/Views/Shared/_LayoutM.cshtml";
}
#Scripts.Render("~/Scripts/charts")
#Styles.Render("~/Content/formsaltcss")
#model Mvc.Models.StudentViewModel
<script type="text/javascript">
$(document).ready(function () {
$('#AddStudentData').click(function () {
var type = 'student';
var id = 0;
$('#holderArea').html('');
if (!$('#studentDropDown option:selected').length) {
ToastrWarning('Please select a student before running the report');
return;
}
id = $('#studentDropDown').val();
var data = { id: id };
$.ajax({
url: '/Student/StudentAnalysisFiltered',
async: false,
data: data,
dataType: 'html',
success: function (data) {
$('#holderArea').html(data);
}
});
});
});
Relevant HTML
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="margin-bottom0 text-center">Student Analysis</h3></div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
<form class="form-horizontal">
<div class="form-group">
<div class="row">
<label class="col-sm-2 control-label">Student Name</label>
<div class="col-sm-4">
#Html.DropDownListFor(c => c.Students, new SelectList(Model.Students, "StudentID", "Name"), "Choose Student"
, new { id = "studentDropDown", #class = "form-control input-sm", data_width = "100%" })
</div>
<div class="col-sm-offset-2 col-sm-10">
<button id="AddStudentData" type="button" class="btn btn-sm btn-primary">Select</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="holderArea">
</div>
StudentAnalysisSelected
Script
#using Data
#using Mvc.Helpers
#model Mvc.Models.StudentViewModel
#Scripts.Render("~/Scripts/datatables")
<script>
function StudentScoresModal(studentID, answer, result) {
$('#scoresTable').hide();
$('#scoresSpinner').show();
$('#scoresModal').modal('show');
var testID = #Html.Raw(Model.testID );
$.ajax({
cache: false,
url: "/Student/StudentScoresDrillthrough",
data: { 'studentID': studentID, 'answer': answer, 'result': result, 'testID': testID},
success: function (data) {
$('#scoresTable').html(data);
$('#scoresTable').show();
$('#scoresSpinner').hide();
},
error: function () {
toastr.options.positionClass = 'toast-bottom-right';
toastr.options.backgroundpositionClass = 'toast-bottom-right';
toastr.options.timeOut = 3000;
toastr.error('Unable to get student results.');
}
});
}
</script>
Relevant HTML
<div id="holderArea">
<button type="button" class="btn btn-sm btn-primary" onclick="StudentScoresModal(id, '', '')" id="#q.StudentID">View Scores</button>
</div>
<div class="modal in modal-stack" id="scoresModal" aria-hidden="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><strong>Student Scores</strong></h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-12">
<div class="table-responsive" id="scoresTable" style="display:none">
</div>
<div class="sk-cube-grid absolute-center top-85" id="scoresSpinner" style="display:none">
<div class="sk-cube sk-cube1"></div>
<div class="sk-cube sk-cube2"></div>
<div class="sk-cube sk-cube3"></div>
<div class="sk-cube sk-cube4"></div>
<div class="sk-cube sk-cube5"></div>
<div class="sk-cube sk-cube6"></div>
<div class="sk-cube sk-cube7"></div>
<div class="sk-cube sk-cube8"></div>
<div class="sk-cube sk-cube9"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
StudentScoresPartial
Script
<script>
$(document).ready(function () {
$('#studentScores').dataTable({
"data": #Html.Raw(Model.StudentScoresJson),
"columns":[
{ "sName": "StudentID" },
{ "sName": "Answer" },
{ "sName": "Result" }
]
});
});
</script>
HTML
<table id="studentScores" class="display table table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>StudentID</th>
<th>Answer</th>
<th>Result</th>
</tr>
</thead>
<tfoot>
<tr>
<th>User</th>
<th>Answer</th>
<th>Response</th>
</tr>
</tfoot>
<tbody></tbody>
</table>
How it all works
On the 'StudentsList' view there is a dropdown with list of students, and a 'Select' button to filter on an individual. OnClick this clears the holderArea div and passes studentID to the controller method, which returns a partial view 'StudentAnalysisSelected' and places it inside the holderArea div.
Now a graph is loaded with details specific to the indivudual. When clicked the 'scoresTable' is hidden and the modal is shown and an ajax call is made to StudentScoresDrillthrough controller, which returns the 'StudentScores' partial that is placed into the html of 'scoresTable'.
The problem
Now this all works perfectly first time I filter by student. I click 'Select', the graph loads, I click the graph and the datatable displays neatly in the modal.
However for reasons unknown to me when I click 'Select' again to re-filter, and click on the graph that is loaded all I see is the modal appear with the loading spinner, and it stops there. No errors pertaining to datatables in the console, or anything out of the ordinary for that matter.
I appreciate this is a bit of a read, but i'd be keen to hear any thoughts on what could be causing my issue.
Thanks!
It's because your dom is reloaded and so you loose your event attached.
If you attach ypur event like so, this should do, see doc :
$('#AddStudentData').on('click',function () {});
First try calling dataTable after filter button click using $('#studentScores').dataTable();
If this doesn't work
Instead on your refilter click write:
$('#studentScores').dataTable();
After your partialview is fully loaded. And bind your list in table directly e.g :
StudentID
Answer
Result
#foreeach(var item in Model)
{
item.User
item.Answer
item.Response
}
Finally tracked it down and it was because the modal show was called before the table show.
Thanks to those who posted suggestions, it's much appreciated
Related
When I render my handlebars template in html, it looks like it's essentially skipping filling in the "handle bars" portion. I'm essentially printing messages with a title and content, and I'm using a "!each" helper to display all of my messages. I originally thought it was because it was because it was escaping the html around it, so I tried using a triple handle bar {{{ on each part however using the each helper with the triple stash gave me an error. Am I possibly using the handlebars incorrectly?
the typescript I used to render the HTML and my handlebars template is below:
public static refreshData(data: any) {
$("#indexMain").html(Handlebars.templates['main.hbs'](data));
//helper function for upvote button
Handlebars.registerHelper('getUButton', function (id) {
id = Handlebars.escapeExpression(id);
return new Handlebars.SafeString(
"<button type='button' class='btn btn-default up-button' id='u" + id + "'>Upvote</button>"
);
});
//helper function for downvote button
Handlebars.registerHelper("getDButton", function (id) {
id = Handlebars.escapeExpression(id);
return new Handlebars.SafeString(
"<button type='button' class='btn btn-default down-button' id='d" + id + "'>DownVote</button>"
);
});
// Grab the template script
var theTemplateScript = $("#main-template").html();
// Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
//get messages from server and add them to the context
// This is the default context, which is passed to the template
var context = {
messages: data
}
console.log("context:")
console.log(context);
// Pass data to the template
var theCompiledHtml = theTemplate(context);
console.log(theCompiledHtml);
// Add the compiled html to the page
$("#messages-placeholder").html(theTemplate(context));
//add all click handlers
//get all buttons with id starting with u and set the click listerer
$(".up-button").click((event) => {
var id = $(event.target).attr("id").substring(1);
main.upvote(id)
});
//get all buttons with id starting with d and set the click listerer
$(".down-button").click((event) => {
var id = $(event.target).attr("id").substring(1);
main.downvote(id)
});
}
<script id="main-template" type="text/x-handlebars-template">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Current Messages</h3>
</div>
<div class="panel-body">
<div class="list-group" id="message-list">
<!-- for each message, create a post for it with title, content, upvote count, and upvote button -->
{{#each messages}}
<li class="list-group-item">
<span class="badge">Vote Count: {{likeCount}}</span>
<h4 class="list-group-item-heading">{{title}}</h4>
<p class="list-group-item-text">{{content}}</p>
<div class="btn-group btn-group-xs" role="group" aria-label="upvote">
{{getUButton id}}
</div>
<div class="btn-group btn-group-xs" role="group" aria-label="downvote">
{{getDButton id}}
</div>
</li>
{{/each}}
</div>
</div>
</div>
</script>
<div id="messages-placeholder"></div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Post New Message</h3>
</div>
<div class="input-group">
<span class="input-group-addon">Title</span>
<input id="newTitle" type="text" class="form-control" placeholder="Title" aria-describedby="newTitle">
</div>
<div class="input-group">
<span class="input-group-addon">Message</span>
<input id="newMessage" type="text" class="form-control" placeholder="Message" aria-describedby="newMessage">
</div>
<div class="btn-group" role="group" aria-label="create">
<button type="button" class="btn btn-default" id="postNewMessage">Post Message</button>
</div>
<span class="label label-danger" id="incompleteAcc"></span>
</div>
Okay, then it is likely the data provided to your template is not in the correct form. Here's a working snippet (with non-essentials stripped out). The data passed to your refreshData template must be an array. Make sure it isn't an object containing an array.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
</head>
<body>
<script>
let refreshData = (data) => {
// Grab the template script
var theTemplateScript = $("#main-template").html();
// Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
//get messages from server and add them to the context
// This is the default context, which is passed to the template
var context = {
messages: data
};
console.log("context:", context);
// Add the compiled html to the page
$("#messages-placeholder").html(theTemplate(context));
}
$(() => {
var data = [
{ likeCount: 3, title: 'My Title', content: 'Some content'},
{ likeCount: 0, title: 'My 2nd Title', content: 'Some other content'}
];
refreshData(data);
})
</script>
<script id="main-template" type="text/x-handlebars-template">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Current Messages</h3>
</div>
<div class="panel-body">
<div class="list-group" id="message-list">
<!-- for each message, create a post for it with title, content, upvote count, and upvote button -->
{{#each messages}}
<li class="list-group-item">
<span class="badge">Vote Count: {{likeCount}}</span>
<h4 class="list-group-item-heading">{{title}}</h4>
<p class="list-group-item-text">{{content}}</p>
</li>
{{/each}}
</div>
</div>
</div>
</script>
<div id="messages-placeholder"></div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Post New Message</h3>
</div>
<div class="input-group">
<span class="input-group-addon">Title</span>
<input id="newTitle" type="text" class="form-control" placeholder="Title" aria-describedby="newTitle">
</div>
<div class="input-group">
<span class="input-group-addon">Message</span>
<input id="newMessage" type="text" class="form-control" placeholder="Message" aria-describedby="newMessage">
</div>
<div class="btn-group" role="group" aria-label="create">
<button type="button" class="btn btn-default" id="postNewMessage">Post Message</button>
</div>
<span class="label label-danger" id="incompleteAcc"></span>
</div>
</body>
</html>
When I am faced with issues like this, I eliminate different things until I either get clarity or something I removed fixes the problem. Now I have isolated where the problem lies. In your situation, the issue is likely the data being passed so verify that. Then try stripping out your helpers to see if they are causing issues.
I have a strongly typed view in which I am looping over some objects from a database and dispaying them in a jumbobox with two buttons in it. When I click one of the buttons I have a modal popping up. I'd like to have somewhere in this modal the name and the id of the corresponding object, but I do not really know how to do this. I am a bit confused where to use c# and where javascript. I am a novice in this, obviously.
Can someone help?
This is the code I have so far. I don't have anything in relation to my question, except the code for the modal :
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" class="modal fade" 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">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
I think your confusing the server side rendering of Razor and the client side rendering of the Modal. The modal cannot access your Model properties as these are rendered server side before providing the page to the user. This is why in your code <h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4> this does not work.
What you want to do is capture the event client side in the browser. Bootstrap allows you to achieve this by allowing you to hook into events of the Modal. What you want to do is hook into the "show" event and in that event capture the data you want from your page and supply that to the Modal. In the "show" event, you have access to the relatedTarget - which is the button that called the modal.
I would go one step further and make things easier by adding what data you need to the button itself as data-xxxx attributes or to DOM elements that can be easily access via JQuery. I have created a sample for you based on what you have shown to give you an idea of how it can be achieved.
Bootply Sample
And if needed... How to specify data attributes in razor
First of all
you will need to remove the data-toggle="modal" and data-target="#myModal" from the button, as we will call it manually from JS and add a class to reference this button later, your final button will be this:
<button type="button" class="btn btn-default btn-lg modal-opener">Had role in the past</button>
Then
In your jumbotron loop, we need to catch the values you want to show later on your modal, we don't want to show it, so we go with hidden inputs:
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
For each information you want to show, you create an input referencing the current loop values.
Now you finally show the modal
Your document.ready function will have this new function:
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
It simply grab those values we placed in hidden inputs.
Your final code
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" class="modal fade" 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">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
I really feel this is a stupid question but I could not figure out:
Here my cshtml file, and it's rendered just fine:
#model CrashTestScheduler.Entity.Model.Channel
#{
string editFormat = string.Format("<button type='button' class='editForm' data-val-id=\"{0}\"><span class='ico-edit'></span></button>", ".Id");
const string DeleteFormat = "<button type='button' class='awe-btn' onclick=\"awe.open('deleteChannel', { params:{ id: .Id } })\"><span class='ico-del'></span></button>";
const string EditFormat = "<button type='button' class='awe-btn' onclick=\"awe.open('editChannel', { params:{ id: .Id } })\"><span class='ico-edit'></span></button>";
}
<script>
$(function() {
awe.popup = bootstrapPopup;
});
var getChannelGroupNameHandler = function (item) {
if (item.ChannelGroupName == null || item.ChannelGroupName=='') {
item.ChannelGroupName = $("#ChannelGroupId option:selected").text();
}
}
</script>
<div id="wrap">
<div id="page-heading">
<ol class="breadcrumb">
<li>Home</li>
<li class="active">Channels</li>
<li style="display:none;"></li>
</ol>
</div>
<div class="container">
<div class="col-md-12" id="gridRowChannels">
<div class="col-md-12">
<div class="panel panel-midnightblue-header">
<div class="panel-heading">
<h3>Channel List</h3>
<div class="options">
</div>
</div>
<div class="panel-body">
<div class="row-sub">
<button type="button" id="btnAddProject" class="btn btn-primary" onclick="awe.open('createChannel')">
Add Channel
</button>
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("createChannel").Url(Url.Action("Create", "ChannelsGrid")).Success("itemCreated('ChannelsGrid',getChannelGroupNameHandler)").OkText("Add").Title("Add Channel")
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("deleteChannel").Url(Url.Action("Delete", "ChannelsGrid")).Success("itemDeleted('ChannelsGrid')").Parameter("gridId", "ChannelsGrid").Height(200).Modal(true).Title("Delete Channel").OkText("Delete")
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("editChannel").Group("Channel").Url(Url.Action("Edit", "ChannelsGrid")).Success("itemUpdated('ChannelsGrid',getChannelGroupNameHandler)").OkText("Save").Title("Edit Channel")
</div>
<div class="row-sub">
#(Html.Awe().Grid("ChannelsGrid")
.Url(Url.Action("GetItems", "ChannelsGrid"))
.Columns(
new Column {Name = "Name", Header = "Channel Name", Sort = Sort.Asc},
new Column {Name = "ChannelGroup.Name", Header = "Channel Group", ClientFormat = ".ChannelGroupName"},
new Column {ClientFormat = DeleteFormat, Width = 50},
new Column {ClientFormat = EditFormat, Width = 50}
)
.Sortable(true)
.SingleColumnSort(true)
.LoadOnParentChange(false)
.PageSize(20)
.Groupable(false))
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12" id="pnlEditproject" style="display: none;">
</div>
</div>
</div>
But I want to use jquery to use jquery validation later on. So here I inserted them to the file.
<script src="~/Scripts/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script>
Now the file could not be rendered and the page keeps loading and loading. Any clues?
Looks like you already have access to jQuery library in this page since you are using...
$(function() {
awe.popup = bootstrapPopup;
});
Please remove the new references and try to view page source to find out the list of libraries that are already available.
How do I use nested models with Backbone Forms List? I want to make a nested model with a custom template, but this is giving an error: "Render of undefined"
I want to make a view by backbone-forms with a custom template. The template is
<div class="container-fluid add-apikey" data-class="add-apikey">
<div class="page-head">
<h2>API Key</h2>
</div>
<div class="cl-mcont">
<div class="row">
<div class="col-sm-12">
<!-- New Zone -->
<div class="block-flat">
<form class="form-horizontal" role="form">
<div class="header">
<h3>Create New API Key</h3>
</div>
<div class="content">
<div class="formAlerts"></div>
<div class="formconfirm"></div>
<div class="required" data-fields="apiName">
</div>
<div class="required" data-fields="notes">
</div>
<div class="required" data-fields="weapons">
</div>
<div class="form-group editmode">
<div class="col-sm-offset-3 col-sm-9">
<button class="btn btn-primary readOnlySave" type="button">Generate Key</button>
<button class="btn btn-default readOnlyCancel">Cancel</button>
</div>
</div>
</div>
</form>
</div>
</div>
<!-- end new zone -->
</div>
</div>
and the js is
//Add api keys
var //util
util = require('./../../../util/util.js'),
apiKeyAddTpl = require('./../templates/apikeyadd.hbs'),
backboneFormList = require('backboneFormsList'),
backboneFormsModal = require('backboneFormsModal');
module.exports = Backbone.Form.extend({
template: apiKeyAddTpl,
schema: {
apiName: {
type: 'Text',
fieldClass: "field-apiName form-group",
editorClass: "form-control editmode"
},
notes: {
type: 'List',
fieldClass: "field-notes form-group",
editorClass: "form-control editmode"
},
weapons: {
type: 'List',
itemType: 'Object',
fieldClass: "field-weapon form-group",
editorClass: "form-control editmode",
subSchema: {
id: 'Number',
name: {
type: 'Text'
}
}
}
}
});
But this is giving me an error when I want to add a field under weapons.
The error is : Cannot read property 'render' of undefined.
You need to extend a View: Backbone.View.extend. This view have a el attribute. You must you must associate this attribute with the form. And the views have a method render that you can override.
Doc: backbone view
I'm using Bootstrap with the latest version of jQuery and am having an issue displaying a modal following a partial update of the page via Ajax.
The modal fires ok multiple times before the UpdateRegister function runs after 60 seconds, after that I receive a "0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'modal'" when I click on the button to open the modal again.
The button that fires the modal ('#cmdAdd') is outside the Div updated by the Ajax call.
The javascript is as below:
$(function() {
// Display Add Visitor modal
$("#cmdAdd").on("click", function () {
var url = "/Visitor/Add/";
$.get(url, function (data) {
$("#myModal").html(data);
$('#myModal').modal('show');
});
});
// Update register every 60 seconds
setInterval(function () {
UpdateRegister();
}, 60000);
});
function UpdateRegister() {
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
var thisDate = month + "/" + day + "/" + year;
var url = "/Visitor/RegisterList?date=" + thisDate + "&filter=current";
$.get(url, function (data) {
$("#RegisterList").html(data);
});
}
HTML is as follows:
<div class="row">
<div class="col-lg-12">
<h2>#Model.Date.DayOfWeek #Model.Date.ToLongDateString()</h2><br />
<div class="btn-group pull-right">
<button type="button" class="btn btn-danger" id="cmdEmergency">Emergency</button>
<button type="button" class="btn btn-default" id="cmdAdd">Add Visitor</button>
<button type="button" class="btn btn-default" id="cmdAddBulk">Add Bulk Visitors</button>
</div>
<ul class="nav nav-tabs">
<li class="active">Current Register <span class="label label-success" id="CountIn">#Model.VisitorsIn</span></li>
<li>Visitors Expected <span class="label label-success">#Model.VisitorsExpected</span></li>
<li>All Visitors <span class="label label-success" id="CountTotal">#Model.TotalVisitors</span></li>
</ul>
<div class="tab-content">
<!-- Visitors currently in the building -->
<div class="tab-pane active" id="register">
<br /><br />
<div class="row">
<div class="col-lg-12">
<div id="RegisterList">
#Html.Action("RegisterList", new { date = Model.Date, filter="current" })
</div>
</div>
</div>
</div>
<!-- Expected visitors not yet arrived -->
<div class="tab-pane" id="expected">
<br /><br />
<div class="row">
<div class="col-lg-12">
<div id="ExpectedList">
#Html.Action("RegisterList", new { date = Model.Date, filter="expected" })
</div>
</div>
</div>
</div>
<!-- All visitors for the day -->
<div class="tab-pane" id="all">
<br /><br />
<div class="row">
<div class="col-lg-12">
<div id="AllList">
#Html.Action("RegisterList", new { date = Model.Date, filter="all" })
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="myModal">
<!-- Modal content goes here -->
</div><!-- /.modal -->
How can I ensure that the modal still works after the update?
I know it sounds trivial but are you possibly missing a reference to bootstrap.js within the AJAX Html? Adding a reference worked for me when I faced the same error.
I think your #myModal just disappear when #RegisterList is set the data. You should go to check about it.