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.
Related
I am using the date picker in admin lte but no mater what I do the date time picker will show.
#Html.LabelFor(model => model.DateReported)
#Html.EditorFor(model => model.DateReported, new { htmlAttributes = new { #class = "form-control
datetimepicker" } })
#Html.ValidationMessageFor(model => model.DateReported)
You will see the generated html is as follows.
<input class="form-control datetimepicker text-box single-line valid" data-val="true" data-val-
required="The DateReported field is required." id="DateReported" name="DateReported" type="datetime-
local" value="0001-01-01T00:00:00.000" aria-required="true" aria-describedby="DateReported-error"
aria-invalid="false">
But even though I have in my scripts done this.
And I have tried this.
#Html.LabelFor(model => model.DateReported)
#Html.EditorFor(model => model.DateReported, new { htmlAttributes = new { #class = "form-control
dateicker" } })
#Html.ValidationMessageFor(model => model.DateReported)
<script type="text/javascript">
$(function () {
$('.DateRaised').datepicker();
$('.DateReported').datepicker();
});
Even if I set it as such Presume its because it gets datetime data type from my model how do I show only date part in textbox.
#Html.LabelFor(model => model.DateReported)
#Html.EditorFor(model => model.DateReported, new { htmlAttributes = new { #class = "form-control
datepicker" } })
#Html.ValidationMessageFor(model => model.DateReported)
But this still procduces this view.
have you tried fixing it from the Model ?
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DateReported{ get; set; }
You should mention the date format on initializing datepicker in Jquery function:
$(function () {
$('.DateRaised').datepicker({
format: 'mm/dd/yyyy',
});
});
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>
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!
My ASP.NET MVC 5 application's razor view uses two checkboxes:
<div class="form-group">
#Html.LabelFor(model => model.BoolField1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { #class = "form-control", #id = "bool1" } })
#Html.ValidationMessageFor(model => model.BoolField1, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BoolField2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.BoolField2, new { htmlAttributes = new { #class = "form-control", #id = "bool2" } })
#Html.ValidationMessageFor(model => model.BoolField2, "", new { #class = "text-danger" })
</div>
</div>
</div>
I'm trying implement the rule that BoolField2 cannot be true unless BoolField1 is also true. My jquery code:
function applyRule() {
var bool1Status = document.getElementById('bool1').checked;
var bool2Status = document.getElementById('bool2').checked;
if (bool2Status == true && bool1Status == false) {
// This is the sole error.
// Generate a suitable error message and display (how?)
}
}
The custom error generated at this code must be displayed into Html.ValidationMessageFor. How can I achieve this?
First you need to correct syntax for EditorFor () it should be like following
#Html.EditorFor(model => model.BoolField1, new { #class = "form-control", #id = "bool1" })
instead of
#Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { #class = "form-control", #id = "bool1" } })
Now after having this correction you may write custom jQuery logic to achieve same. Here is the code.
$(function () {
$('#bool2').on('click', function (e) {
//Get the state of 1st checkbox
var isFirstCheck = $('#bool1').is(":checked");
if (isFirstCheck==false) {
//dispay message if you need. Below line of code will prevent user to select 2nd checkbox
e.preventDefault();
}
})
});
I am using the following JS.fiddle of client-side validation within my project.
I have implemented this example as my javascript.
http://jsfiddle.net/rtglenn/VwPaR/
Currently, the fields are highlighting green when active and staying green. However, they are not displaying red if one of the rules is broken.
Here is my View:
#using (Html.BeginForm()
{
<div class="form-horizontal">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group has-feedback">
<div class="float:left">
#Html.Label("First Name:", htmlAttributes: new { #class = "control-label col-md-2", #for = "fname" })
<div class="col-md-3">
#Html.EditorFor(model => model.Person.fName, new { htmlAttributes = new { #class = "form-control" }, name = "fname", id = "fname" })
#Html.ValidationMessageFor(model => model.Person.fName, "", new { #class = "text-danger" })
</div>
</div>
Any help on this issue would be greatly appreciated. I have checked that my referenced scripts are in the correct order.
Look at the output of #Html.EditorFor(model => model.Person.fName, new { htmlAttributes = new { #class = "form-control" }}), your input name attributes are being assigned the values Person.fName and Person.lName, respectfully.
Your rules need to correlate to those name values.
rules: {
"Person.fName" : {
minlength: 3,
maxlength: 15,
required: true
},
"Person.lName" : {
minlength: 3,
maxlength: 15,
required: true
}
},
for visual feedback, add this to your css:
.form-control.has-error input,
.has-error input
{
background-color:red;
color:white;
}
Of course, there are alternative validation frameworks and methodologies. One of which ships with MVC: Unobtrusive Client Validation in ASP.NET MVC 3 (older post).
Related SO Q&A: What is jQuery Unobtrusive Validation?