Bootstrap selectpicker MVC dropdown livesearch - javascript

I am quite sure my problem is something to do with the script reference.
I have added it to my bundles
bundles.Add(new ScriptBundle("~/bundles/bootstrap-select").Include(
"~/Scripts/bootstrap-select.js",
"~/Scripts/bootstrap-select.min.js"));
here is my views code:
<script type="text/javascript">
$(document).ready(function () {
$('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
});
Html form:
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.SagId, "SagId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.SagId,(IEnumerable<SelectListItem>)ViewBag.SagId,
new
{
#class = "form-control selectpicker",
data_show_subtext = "true",
data_live_search = "true"
})
#Html.ValidationMessageFor(model => model.SagId, "", new { #class = "text-danger" })
</div>
</div>
I get the list from my view bag, that works fine. But I cannot seem to fix this problem.
Update:
tried to manually add referrences in the view. now the dropbox is completly gone and i get theese errors:
Uncaught TypeError: Cannot read property 'valHooks' of undefined
at bootstrap-select.min.js:7
at bootstrap-select.min.js:8
at bootstrap-select.min.js:7
at bootstrap-select.min.js:7
Create:78 Uncaught ReferenceError: $ is not defined
at Create:78

First, you only want to add one of the references; start with just the JS; when built in release mode, it will find the min.js.
bundles.Add(new ScriptBundle("~/bundles/bootstrap-select").Include(
"~/Scripts/bootstrap-select.js"));
This was registering the same script, which will have these sorts of problems.
Secondly, it looks like this bundle is defined before wherever you have JQuery defined. So the $ is not defined is likely because bootstrap select script, and usage, has to be after the JQuery initialization.

Related

Bootstrap 3 DateTimePicker in EditorTemplate

Created an Editor Template to dynamically create time slots. Now I am unable to select the time with datetimepicker. Code below. The following code works when apart of the main view. Is it possible to use datetimepicker in an editortemplate?
#model Testing.Models.TimeSlot
<div class="form-group row">
#Html.LabelFor(model => model.StartTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-2">
#Html.EditorFor(model => model.StartTime, new { htmlAttributes = new { #Value = DateTime.Now.ToString("hh:mm tt"), #class = "form-control", #style = "width: 100px"} })
#Html.ValidationMessageFor(model => model.StartTime, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.EndTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-2">
#Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { #Value = DateTime.Now.AddMinutes(15).ToString("hh:mm tt"), #class = "form-control", #style = "width: 100px" } })
#Html.ValidationMessageFor(model => model.EndTime, "", new { #class = "text-danger" })
</div>
</div>
#section Scripts
{
<script type="text/javascript">
$(function () {
$('#StartTime').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15,
});
});
$(function () {
$('#EndTime').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15
});
});
$('#StartTime').removeAttr("data-val-date");
$('#EndTime').removeAttr("data-val-date");
</script>
Sections are not supported in partials, and your scripts are never included in the html returned to the client. In any case, scripts should never be in partials (which is what an EditorTemplate is) - you are generating inline scripts, making it harder to debug and risk including multiple instances of the scripts.
Delete the #section Scripts{ ... } code from your EditorTemplate and move it to the main view or its layout. To make this a bit more flexible, I recommend you give the inputs a class name, and use that as a jQuery selector, rather that referring to each individual id (and therefore only one script is required).
In addition, you should never set the value attribute when using the HtmlHelper methods. The methods correctly generate the value from ModelState, ViewData and finally the model property in that order, and by setting the value attribute, you are screwing up model binding. Instead, set the values in the GET method before you pass the model to the view.
Your code to generate the datepicker should be just
#Html.EditorFor(m => m.StartTime, new { htmlAttributes = new { #class = "form-control datetimepicker" } })
or more simply
#Html.TextBoxFor(m => m.StartTime, new { #class = "form-control datetimepicker" })
and you can then style the width
.datetimepicker {
width: 100px;
}
and the the script in the view or layout will be just
$('.datetimepicker').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15,
});
Its also not clear why you want to attempt to remove client side validation using .removeAttr("data-val-date"), and doing so suggests a problem with your design. It also appears that you want to select a time only, in which case your property should be TimeSpan.

using jQuery UI Datepicker in MVC razor getting error

I am following this example to use jQuery UI Datepicker in my MVC project.
Model
[DataType(DataType.Date)]
public DateTime RequestDate { get; set; }
Razor
<div class="form-group">
#Html.LabelFor(model => model.RequestDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RequestDate)
#Html.ValidationMessageFor(model => model.RequestDate, "", new { #class = "text-danger" })
</div>
Then as per tutorial created Date helper and pasted this line
#Html.TextBox("", String.Format("{0:d}", (string)Model.ToShortDateString()), new { #class = "datefield", #type = "date" })
When i run the application, i get run time exception for above line. Model is null. I am not sure why? and How does it bind to my model?
Additional information: Cannot perform runtime binding on a null
reference
DatePickerReady.js
if (!Modernizr.inputtypes.date) {
$(function () {
$(".datefield").datepicker();
});
}
I think your problem is caused by the casting part of (string)Model.ToShortDateString(), no need for the casting here as the ToShortDateString will return a string anyways. Try this instead:
#Html.TextBox("", String.Format("{0:d}", Model.ToShortDateString()),
new { #class = "datefield", #type = "date" })
And you need to make sure to name your editor template a name matching your data type (DateTime.cshtml in your case) or use the UIHint attribute if you like to customize the name, and make sure you add your template under the proper EditorTemplates folder.

JQuery chosen not closing on select

I am using a JQuery chosen control. It remains open after item selection, also before clicking on it, it is displaying the search textbox. I don't want either of these things to be happening.
Here's the code for the dropdown in MVC using EF:
<div class="form-group">
#Html.LabelFor(model => model.Field, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Field, null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Field, "", new { #class = "text-danger" })
</div>
</div>
Here's the script:
<script type="text/javascript">
$("#Field").chosen();
</script>
what am I missing here. I thought this behaviour was there by default?
Edit: To anyone else having this problem - I forgot to link the chosen.css
Try this;
<script type="text/javascript">
$("#Field").chosen({
max_selected_options: 1,
allow_single_deselect: true, // check out what happens when you remove this option
disable_search: true, // if you dont want to show search box
}).removeAttr("multiple");
$("#Field").on("chosen:maxselected",function(evt, params){
$('#Field').trigger('chosen:close');
});
</script>

If checkbox is checked then enable EditorFor

I would like my Checkbox to disable EditorsFor if it is unchecked and enable them if it is checked. I know I have to use JavaScript, I found some codes in net, but it seems that they don't work.
Here is my View code:
#{Html.RenderPartial("_PartialError");}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
(...)
<div class="form-group">
#Html.LabelFor(model => model.Czy_zuzywalny, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Czy_zuzywalny)
#Html.ValidationMessageFor(model => model.Czy_zuzywalny, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Ilosc_minimalna, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ilosc_minimalna, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ilosc_minimalna, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Ilosc_optymalna, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ilosc_optymalna, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ilosc_optymalna, "", new { #class = "text-danger" })
</div>
</div>
(...)
}
And I wrote something like this and put in js file (ofc at the end of this code is ), but it doesn't work...
$(document).ready(function ()
{
$("#Czy_zuzywalny").click(function ()
{
if ($("#Ilosc_minimalna").attr("disabled") == "")
{
$("#Ilosc_minimalna").attr("disabled", "disabled");
$("#Ilosc_optymalna").attr("disabled", "disabled");
$("#Ilosc_minimalna").attr("value", "0");
$("#Ilosc_optymalna").attr("value", "0");
}
else
{
$("#Ilosc_minimalna").attr("disabled", "");
$("#Ilosc_optymalna").attr("disabled", "");
}
});
});
Nothing happens even if I check or uncheck my checkbox. Can anyone help me with that?
Change your jQuery code to:
$(document).ready(function () {
$("#Czy_zuzywalny").click(function () {
if ($("#Ilosc_minimalna").is('[disabled=disabled]')) {
$("#Ilosc_minimalna").removeAttr("disabled");
$("#Ilosc_optymalna").removeAttr("disabled");
}
else {
$("#Ilosc_minimalna").attr("disabled", "disabled");
$("#Ilosc_optymalna").attr("disabled", "disabled");
$("#Ilosc_minimalna").attr("value", "0");
$("#Ilosc_optymalna").attr("value", "0");
}
});
});
The if condition on your code never actually evaluates to true because in an enabled input, the 'disabled' attribute doesn't have a value of an empty string. it just doesn't exist (thus the use of removeAttr("disabled")).
UPDATE: Working JSFiddle here
UPDATE 2:
In order to add the script in the Create view and have it show after the jQuery script tag in the rendered HTML do this:
First add a call to RenderSection in your Layout file just before the closing </body> tag like this:
#RenderSection("scripts", required: false)
This will give you the ability to include a 'scripts' section in your views, the contents of which, will appear instead of the RenderSection call in the final HTML. Note that the required: false parameter specifies that you don't have to include this section in every view.
Then in your Create view, outside of any section add this:
#section scripts {
<script src="/scripts/CheckBoxItemCreate.js"></script>
}
Hope this helps!

jquery ui datepicker error

This is the error message I get when try to implement the datepicker:
Unhandled exception at line 133, column 9 - JavaScript runtime error: Object doesn't support property or method 'datepicker'
This is the code I have added to the View:
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>`
Here is the script:
<script>
$(function () {
$("#model.Date").datepicker();
});
This is my first jQuery element so I don't know what I am doing wrong. I don't understand the entire jQuery element process.
datepicker() is not a method in plain jQuery. It is part of the jQueryUI library, which you will also need to include in your page:
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jqueryui.js"></script>
<script type="text/javascript">
$(function () {
$("#model.Date").datepicker();
});
</script>
</head>
The jQueryUI library can be downloaded from http://jqueryui.com

Categories

Resources