jQuery bootstrap multiselect dropdown not getting loaded - c#

I am trying to use bootstrap multiselect plugin in one of my ASPX pages. Along with the multiselect plugin I have several other jQuery controls in the same page (like autocomplete textbox etc) and some client side validations as well. Following is my bootstrap multiselect code:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<link href="Styles/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="Styles/StyleSheetMasterDataForm.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="Styles/bootstrap-3.1.1.min.css" type="text/css" />
<link rel="stylesheet" href="Styles/bootstrap-multiselect.css" type="text/css" />
<script src="Scripts/jquery-1.11.2.js" type="text/javascript"></script>
<script type="text/javascript" src="Scripts/bootstrap-2.3.2.min.js"></script>
<script type="text/javascript" src="Scripts/bootstrap-multiselect.js"></script>
<script src="Scripts/jquery-ui.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui.min.js" type="text/javascript"></script>
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function () {
debugger;
$("[id*=ListBoxProdEngine]").multiselect({
includeSelectAllOption: true
});
}); //Ending document.ready
</script>
HTML code:
<tr>
<td class="style6"><div class="style8"><strong>Product Engine:</strong></div></td>
<td class="style2"><asp:ListBox ID="ListBoxProdEngine" multiple="multiple" runat="server"></asp:ListBox></td>
</tr>
Code behind:
private void PopulateProductEngine()
{
try
{
ProductEngine objProductEngine = new ProductEngine();
ListBoxProdEngine.DataSource = objProductEngine.GetProductEngine();
ListBoxProdEngine.DataTextField = "ProductEngine";
ListBoxProdEngine.DataValueField = "ProductEngine";
ListBoxProdEngine.DataBind();
}
catch (Exception ex)
{
ErrorHandler.ReportError(ex); //Notifies technical team about the error
Server.ClearError();
Response.Redirect(string.Format("Error.aspx?aspxerrorpath={0}", Request.Url.PathAndQuery));
}
}
The error encountered is in the "multiselect" function in document.ready. Please help.

Related

C# How to pass model to Vue + typescript?

Assuming I have following *.cshtml file with my object already in place (#Model.Configuration) I would like to have it in the rendered Vue.js page built with type script (App.vue or Home.vue). How to do it for first-name id or it's easier to do with window.Configuration ?
*.cshtml
#model Views.Home.HomeViewModel;
#{
var cdnPath = #Model.Configuration.Path;
}
<html>
<head>
<title>#Model.Configuration.Lastname page</title>
<link href="#(cdnPath)js/app.js" rel="preload" as="script">
<link href="#(cdnPath)js/chunk-vendors.js" rel="preload" as="script">
<link rel=stylesheet href="#(cdnPath)css/chunk-vendors.css" />
<link rel=stylesheet href="#(cdnPath)css/app.css" />
</head>
<body>
<div id="configuration">
<p id="first-name">#Model.Configuration.Firstname</p>
</div>
<div id="app">
</div>
<script type="text/javascript" src="#(cdnPath)js/chunk-vendors.js"></script>
<script type="text/javascript" src="#(cdnPath)js/app.js"></script>
<script>window.Configuration = #Html.Raw(Json.Serialize(Model.Configuration));</script>
</body>
main.ts
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import dictionary from "./dictionary";
import './plugins/coreui'
import './plugins/bootstrap-vue'
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");

Adding Toast in the ASP.Net Core Razor page

I am currently building my first ASP.Net core application with Razor pages, where I am trying to add the toast to screen on when an item is successfully added to cart which is a click event on the Add to Cart link. I added the logic but is not working as expected. I followed link and below is the Index.cshtml where I am trying to show toast
<div class="toast">
<div class="toast-body">
Successfully added item to the cart
</div>
</div>
.............
<td>
.....
Add to Cart
......
</td>
.........
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", "#buyNow", (function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var id=$(this).data("id");
onBuyNow(id);
}));
function onBuyNow(id) {
.........
$.ajax({
type: 'POST',
url: '#Url.Action("OrderItem", "Inventories")',
data: data,
dataType: "json",
success: function (result) {
if (result !== "")
{
//showing validation errors
.........
}
else {
// Navigates to the same page back and thats where I am trying to show toast
var url = '#Url.Action("Index", "Inventories")';
window.location.href = `${url}?id=${customerId}&rmID=${#HttpContextAccessor.HttpContext.Request.Query["rmID"]}`;
// trying to show toast on success
$('.toast').toast('show');
}
},
error: function (error) {
alert(error);
}
});
};
});
</script>
No toast shows up when the item got added to cart successfully. I already have references to the bootstrap in the _Layout.cshtml
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>App Name</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.7.0/font/bootstrap-icons.css">
</head>
Any help is greatly appreciated
**** EDIT***
Before adding the new references in the _Layout.cshtml, it shows the navigation and all
After adding the suggested new refreneces like
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>App Name</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.7.0/font/bootstrap-icons.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
The issue is it takes off the pagination from the index page and it appears like below table and the footer
I have checked your code. Seems problem on your script library
references. It’s not correct. The link you have followed they shared
the link as well which you haven't used. So the take away is, for
toast it requires particular library that's why you are not getting
it.
Your Sample Code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="toast">
<div class="toast-body">
Successfully added item to the cart
</div>
</div>
<td>
Add to Cart
</td>
<script>
$(document).ready(function () {
$("#buyNow").click(function (e) {
var id = 5;
onBuyNow(id);
});
function onBuyNow(id) {
alert("Your Product Id is : " +id);
$('.toast').toast('show');
}
});
</script>
</body>
</html>
Output:
Note: Remember to add required script link. Additionally, for internal link make sure you have those script library locally. Other
than toast will not work. You can have a look official document here
Self-define toast without any script:
<div id="toast" class="toast" style="position: fixed; margin-left:250px; bottom: 800px;font-weight: 400;line-height: 1.5; color: !important #212529; width: 100%; max-width: 300px;border: 1px solid rgba(0,0,0,.1);box-shadow: 0 0.5rem 1rem; border-radius: 0.25rem; background-color: rgba(255,255,255,.85); color: #6c757d; font-size: 16px; padding: 10px; user-select: none;">
<div class="toast-header">
Toast Header
</div>
<div class="toast-body">
Successfully added item to the cart
</div>
</div>
<td>
Add to Cart
</td>
Self define script:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
$("#toast").hide();
$("#buyNow").click(function (e) {
var id = 5;
onBuyNow(id);
});
function onBuyNow(id) {
$("#toast").show();
$("#toast").show().delay(2000).fadeOut();
}
});
</script>
}
Output:
Remarks: if you want to align the toast-box position please modify margin-left:250px; bottom: 800px these property as per your
needs. Hope it would guide you to resolve the issue and save much
time.

Failed to load resource: Uncaught TypeError: $(...).select2 is not a function

So my MVC application keeps on throwing an Http internal server error with status code 500 when it renders my view.
The error it is throwing is a JQuery "Uncaught TypeError: $(...).select2 is not a function"
Uncaught TypeError: $(...).select2 is not a function
at HTMLDocument.<anonymous> (AddUser:381)
at fire (jquery-1.11.0.js:3100)
at Object.fireWith [as resolveWith] (jquery-1.11.0.js:3212)
at Function.ready (jquery-1.11.0.js:3424)
at HTMLDocument.completed (jquery-1.11.0.js:3454)
Using debugger tools, it throws the error here:
$('selectUser').select2();
This is how I call my script:
#section Scripts {
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/jquery-ui-1.8.16.custom.min.js")"></script>
#Scripts.Render("~/bundles/forms")
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('selectUser').select2();
});
</script>
Some SO posts suggest that this error is caused when you omit type="text/javascript"in your script tag or when you call the select2 function before the reference to the CDN service but as it clearly shows on my code all seems fine regarding the aforementioned.
According to this Uncaught TypeError: $(...).select2 is not a function, I am told to make sure if I have one version of JQuery loaded and all seems fine
Here is some additional code from my View that will help in reproducing the problem:
<script>
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.userId = jQuery('#selectUser').val();
model.rolesList = usersRoles;
console.log('model: ' + 'user: ' + model.userId + 'roles: ' + model.rolesList);
console.log('JSON: ' + JSON.stringify(model));
jQuery('#loading3').show();
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { showSuccessMessage(data); },
failure: function (errMsg) {
jQuery('#loading3').hide();
alert(errMsg);
}
});
return false;
}
//Shows the success message
function showSuccessMessage(data) {
jQuery('#loading3').hide();
alert(data);
}
</script>
Controller:
public ActionResult AddUser()
{
if (TempData["StatusMessage"] != null)
{
ViewBag.StatusMessage = TempData["StatusMessage"].ToString();
}
else
{
ViewBag.StatusMessage = "";
}
AddUserToRolesViewModel vm = new AddUserToRolesViewModel();
vm.Users = db.Users.ToList();
return View(vm);
}
EDIT:
Just to make sure that JQuery Core didn't load twice (once in Master and once in Content page) - I have included the markup for my master page.
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="shortcut icon" href="/favicon.ico" />
#Styles.Render("~/Content/Template/css/style.css")
<!--[if IE 9]>
<link rel="stylesheet" media="screen" href="#Url.Content("~/Content/Template/css/ie9.css")"/>
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" media="screen" href="#Url.Content("~/Content/Template/css/ie8.css")"/>
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" media="screen" href="#Url.Content("~/Content/Template/css/ie7.css")"/>
<![endif]-->
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/custom/general.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/ui.spinner.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/jquery.jgrowl.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/jquery.alerts.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/custom/elements.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/colorpicker.js")"></script>
<!--[if lt IE 9]>
<script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
<![endif]-->
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/excanvas.min.js")"></script><![endif]-->
<title>#ViewBag.Title</title>
</head>
<body class="loggedin">
#Html.Partial("_Header_top")
<!-- START OF MAIN CONTENT -->
<div class="mainwrapper">
<div class="mainwrapperinner">
#Html.Partial("_Menu_left")
<div class="maincontent">
<div class="maincontentinner">
#RenderBody()
</div>
<div class="footer">
#Html.Partial("_Footer")
</div>
</div>
</div>
</div><!--mainwrapper-->
<!-- END OF MAIN CONTENT -->
</body>
#RenderSection("scripts", required: false)
#Scripts.Render("~/bundles/jqueryval")
</html>
Update II:
So I went ahead to my App_Start folder and navigated to my BundleConfig.cs and there I noticed something:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~/Content/Template/js/plugins/jquery-ui-
1.8.16.custom.min.js"
}
According to this link: Usage of the ASP.NET MVC4 jquery/javascript bundles and I realized that file "~/Content/Template/js/plugins/jquery-ui-1.8.16.custom.min.js" had alreasdy been added to this bundle and referenced in my content page (AddUser.cshtml) as:
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/jquery-ui-1.8.16.custom.min.js")"></script>
At this point, I strongly believed this was going to fix the problem and so I removed this reference in my content page because I believed that that could be loading JQuery core twice but still nothing. The error still persists. What else can I do to try solve this?
Worthy mention that this error persists across all browsers (Chrome, IE & Firefox)

Jquery .show hides again after postback

I have an UL that I control using hide and show. The problem is that when I click on level1 it shows level2 for only a moment before it disappears, I believe this is because of a postback or something. The functionality works but it just doesnt stay like it. I need to be able to toggle the items in the list to show and hide them.
<script>
$(function(){
$('.level2').hide();
$('.level3').hide();
$('.level1').click(function () {
$('.level2').show();
return false;
$('level2').click(function () {
$('.level3').show();
return false;
$(this).find('ul').slideToggle();
});
})
}
)
</script>
HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<title></title>
<link href="styles/Menu.css" rel="stylesheet" />
<script type="text/javascript">
function openNewWin(url) {
var x = window.open(url, 'mynewwin', 'toolbar=no,directories=no,location=no,menubar=no,left=0,top=0,resizable=no,status=no');
x.focus();
}
</script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css"/>
<script>
$(function(){
$('.level2').hide();
$('.level3').hide();
$('.level1').click(function () {
$('.level2').show();
return false;
$('level2').click(function () {
$('.level3').show();
return false;
$(this).find('ul').slideToggle();
});
})
}
)
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="menu" class="MenuBar">
<asp:Menu ID="Menu1" runat="server" CssClass="mainmenu" StaticDisplayLevels="3" Target="_blank" StaticEnableDefaultPopOutImage="False" StaticSubMenuIndent="0px" >
<LevelMenuItemStyles>
<asp:MenuItemStyle CssClass="level1"/>
<asp:MenuItemStyle CssClass="level2"/>
<asp:MenuItemStyle CssClass="level3" />
<asp:MenuItemStyle CssClass="level4" />
</LevelMenuItemStyles>
<StaticMenuItemStyle CssClass="staticItem" />
</asp:Menu>
</div>
</form>
</body>
</html>

jQuery Function "undefined" according to Visual Studio 2010

This may be a pretty simple question about jQuery UI and Javascript, but I am still feeling my way through these syntax's. I am trying to update a jQuery progress bar whenever my C# (ASP.NET) program reaches a certain point in different functions. Am I doing this correctly? I can see the empty progress bar on my page, but I cannot get it to update its progress.
Here are my scripts:
<script type="text/javascript">
$(document).ready(function() {
$("#progressbar").progressbar({ value: 0 });
});
function updateProgress(number) {
if (number < 100) {
$("#progressbar").progressbar("value", number);
}
}
</script>
Here are some more of my script references:
<link href="Styles/tomcat.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="colorbox.css" />
<script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.8.21.custom.js" type="text/javascript"></script>
<script type="text/javascript" src="Scripts/jquery.colorbox.js"></script>
<link href="Content/themes/base/jquery.ui.progressbar.css" rel="stylesheet" type="text/css" />
<link href="Content/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery.ui.core.js" type="text/javascript"></script>
<link href="Scripts/jquery-ui-1.8.21.custom.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery.ui.progressbar.js" type="text/javascript"></script>
<link href="Scripts/ui.all.css" rel="stylesheet" type="text/css" />
And here is where I try to use the updateProgress() function via a C# function. I am trying to send "10%" to the progress bar but my debugger errors out and says that updateProgress() is not defined.
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>UpdateProgress(10);</script>", false);
EDIT: I added the following boolean to bypass the page refreshing and refreshing my progress bar.
var runOnce = new Boolean;
runOnce = false;
$(document).ready(function() {
if(!runOnce)
{
$("#progressbar").progressbar({ value: 0 });
runOnce = true;
}
});
I don't think it is working though. It still clears and sets it back to zero every page load.
javascript is case sensitive. either change your function declaration to UpdateProgress or change your injection to updateProgress.
also i believe you should including type="text/javascript" on your script tag - language is a deprecated attribute. related: What is the difference between "lang" and "type" attributes in a script tag?
Edit: to handle the progress getting overwritten:
var progressAlreadySet;
$(document).ready(function() {
$("#progressbar").progressbar(); // initialize
if (!progressAlreadySet) {
$("#progressbar").progressbar("value", 0);
}
});
var updateProgress = function (number) {
if (number < 100) {
progressAlreadySet = true;
$("#progressbar").progressbar("value", number);
}
};

Categories