Setting default date for datepicker in mvc - asp.net-mvc

I have implemented moment js for my datepicker in a MVC website but I cant get the default date to work. I just shows 1. january 2015. I want it to show todays date.
Model
public class TeamModel
{
public Team Team { get; set; }
}
Controller. I set my start and end date:
model.Team = new Team();
model.Team.StartDate = DateTime.Today;
model.Team.EndDate = DateTime.Now.AddDays(30);
In my View I have the js:
<script type="text/javascript">
$(function () {
moment.lang('da');
$('#Team_StartDate').datetimepicker({
locale: 'da',
format: 'D-MMMM-YYYY',
showClose: true,
showClear: true,
toolbarPlacement: 'top'
});
$('#Team_EndDate').datetimepicker({
locale: 'da',
format: 'D-MMMM-YYYY',
showClose: true,
showClear: true,
toolbarPlacement: 'top'
});
});
</script>
and the editorfor
<div class="form-group">
#Html.LabelFor(model => model.Team.StartDate, htmlAttributes:
new { #class = "control-label col-md-2" })
<div>
#Html.EditorFor(model => model.Team.StartDate, new {
#Value = Model.Team.StartDate.ToString(), htmlAttributes =
new { #class = "form-control" } })
#Html.ValidationMessageFor(model =>
model.Team.StartDate, "", new { #class = "text-danger" })
</div>
</div>
But the date displayed in StartDate is "1-januar-2015" and "31-januar-2015" in EndDate.

Related

ASP.NET MVC return 500 for dropdownlist cascading

Am using it for cascading dropdownlist for country and state. When I click on
country dropdownlist that suppose to display states, I got 500 server error. Please help me
The error occurs when I click the Country dropdownlist
[HttpPost]
[ValidateAntiForgeryToken] //this is to prevent CSRF attack
public ActionResult Create(CITIES ci)
{
List<COUNTRIES> allCountry = new List<COUNTRIES>();
List<STATES> allState = new List<STATES>();
using (AdminEntities dc = new AdminEntities())
{
allCountry = dc.COUNTRIES.OrderBy(a => a.COUNTRY_NAME).ToList();
if (ci != null && ci.COUNTRY_ID > 0)
{
allState = dc.STATES.Where(a => a.COUNTRY_ID.Equals(ci.COUNTRY_ID)).OrderBy(a => a.STATE_NAME).ToList();
}
}
ViewBag.COUNTRY_ID = new SelectList(allCountry, "COUNTRY_ID", "COUNTRY_NAME", ci.COUNTRY_ID);
ViewBag.STATE_ID = new SelectList(allState, "STATE_ID", "STATE_NAME", ci.STATE_ID);
if (ModelState.IsValid)
{
using (AdminEntities dc = new AdminEntities())
{
dc.CITIES.Add(ci);
dc.SaveChanges();
ModelState.Clear();
ci = null;
ViewBag.Message = "Successfully Saved";
}
}
else
{
ViewBag.Message = "Failed! Please try again";
}
return View(ci);
}
[HttpGet]
public JsonResult GetStates(string countryID = "")
{
// List<COUNTRIES> allCountry = new List<COUNTRIES>();
List<STATES> allState = new List<STATES>();
int ID = 0;
if (int.TryParse(countryID, out ID))
{
using (AdminEntities dc = new AdminEntities())
{
allState = dc.STATES.Where(a => a.COUNTRY_ID.Equals(ID)).OrderBy(a => a.STATE_NAME).ToList();
}
}
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data = allState,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
return new JsonResult
{
Data = "Not valid request",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
view
#model BPP.CCSP.Admin.Web.Models.CITIES
Create
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="form-horizontal">
<h4>CITIES</h4>
<hr />
#if(ViewBag.message != true)
{
<div style="border:solid 1px black">
#ViewBag.message
</div>
}
<div class="form-group">
#Html.LabelFor(model => model.COUNTRY_ID, "COUNTRY_ID", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#* #Html.DropDownListFor(model=>model.COUNTRY_ID, new SelectList(string.Empty, "Value", "Text"), "Please select a country", new { #style = "width:250px;" }) *#
#Html.DropDownListFor(model => model.COUNTRY_ID, #ViewBag.COUNTRY_ID as SelectList,"Select Country")
#Html.ValidationMessageFor(model => model.COUNTRY_ID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.STATE_ID, "STATE_ID", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#* #Html.DropDownListFor(model => model.STATE_ID, new SelectList(string.Empty, "Value", "Text"), "Please select a state", new { #style = "width:250px;" }) *#
#Html.DropDownListFor(model => model.STATE_ID, #ViewBag.STATE_ID as SelectList, "Select State")
#Html.ValidationMessageFor(model => model.STATE_ID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CITY_NAME, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CITY_NAME)
#Html.ValidationMessageFor(model => model.CITY_NAME)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script language="javascript">
$(document).ready(function () {
$("#COUNTRY_ID").change(function () {
//this will call when country dropdown select change
var countryID = parseInt($("#COUNTRY_ID").val());
if (!isNaN(countryID))
{
var ddState = $("#STATE_ID");
ddState.empty(); //this line is to clear all items from statee dropdown
ddState.append($("<option></option>").val("").html("Select State"));
//here i will call controller action via jquery to load state for selected country
$.ajax({
url: "#Url.Action("GetStates","CITIES")",
type: "GET",
data: {countryID : countryID},
dataType: "json",
success: function (data)
{
$.each(data, function (i, val) {
ddState.append(
$("<option></option>").val(val.STATE_ID).html(val.STATE_NAME)
);
});
}
,
error: function ()
{
alert("Error!");
}
});
}
});
});
</script>
}
Please what do I do
can you try
var data = {"countryID" : countryID};
$.ajax({
url: '#Url.Content("~/CITIES/GetStates")',
type: "GET",
contentType: 'application/json',
data:JSON.stringify(data),
});
and then debug GetStates action and if you get error there you will get normally 500 server error

Updating the month in kendo datetime control based on value entered in the text control

I am working on MVC application. Trying to the add the months to Kendo MVC Datetimepicker control based on the change event of text box control.
When the user enters the months in the Contract Duration field it should add Priority Date time control.
Could somebody advice how it can be done.
Contract Duration in Months
<div class="form-group">
#Html.LabelFor(model => model.ContractDurationInMonths, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.ContractDurationInMonths, new { htmlAttributes = new { #class = "form-control", style = "width:100%" } })
#Html.ValidationMessageFor(model => model.ContractDurationInMonths, "", new { #class = "text-danger" })
</div>
</div>
Priority Datetime control
<div class="form-group">
#Html.LabelFor(model => model.Priority, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#*#Html.EditorFor(model => model.Priority, new { htmlAttributes = new { #class = "form-control" } })*#
#(Html.Kendo().DatePickerFor(model => model.Priority)
.Name("Priority")
.Value("10/10/2011")
.HtmlAttributes(new { style = "width: 100%" })
)
#Html.ValidationMessageFor(model => model.Priority, "", new { #class = "text-danger" })
</div>
</div>
Basically, set the blur() event on your textbox then update the value of datepicker:
<script>
$(document).ready(function() {
$("#ContractDurationInMonths").blur(function () {
var date = $("#Priority").data("kendoDatePicker").value();
var newMonth = date.getMonth() + kendo.parseInt($("#ContractDurationInMonths").val());
date.setMonth(newMonth);
$("#Priority").data("kendoDatePicker").value(date);
});
});
</script>
Here is an example in js: http://dojo.telerik.com/#sg53719/eseRo

Bootstrap 3 Eonasdan DatetimePicker Stops submiting Form

I have added Bootstrap 3 eonasdan-datetimepicker. When I Select Datetimepicker
it gives focus to that particular Datetimepicker
and when i click on submit button, Submit button prevents submitting form and
opens datetimepicker-dialog as if it becomes part of datetimepicker
My ViewModel:
[Display(Name = "From")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime From { get; set; }
[Display(Name = "To")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime To { get; set; }
And View Is:
<div class="form-group">
#Html.LabelFor(model => model.From, htmlAttributes: new { #class = "control-label col-lg-4 col-md-4" })
<div class="col-lg-6 col-md-6">
#Html.TextBoxFor(model => model.From, new { #class = "form-control datetime"})
#Html.ValidationMessageFor(model => model.From, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.To, htmlAttributes: new { #class = "control-label col-lg-4 col-md-4" })
<div class="col-lg-6 col-md-6">
#Html.TextBoxFor(model => model.To, new { #class = "form-control datetime" })
#Html.ValidationMessageFor(model => model.To, "", new { #class = "text-danger" })
</div>
</div>
#section Styles{
#Styles.Render("~/Content/jqueryui")
#Styles.Render("~/Content/datetimepicker")
}
#section Scripts{
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/datetimepicker")
<script type="text/javascript">
$(function () {
//setting datetime picker.
$('#From').datetimepicker({ format: 'DD/MM/YYYY'});
$('#To').datetimepicker({
useCurrent: false, //Important! See issue #1075
format: 'DD/MM/YYYY'
});
$("#From").on("dp.change", function (e) {
$('#To').data("DateTimePicker").minDate(e.date);
});
$("#To").on("dp.change", function (e) {
$('#From').data("DateTimePicker").maxDate(e.date);
});
});
</script>
}

ValidationMessageFor return all the time error

I am using the jquery validation script, in addition, I create a validation on the server side. for some reason, I got all the time error message from the server even when the text fields values are correctly defined.
this is my view file:
#model StudentsManagment.Models.student
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal" id="studentForm">
<h4>Student</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.First_name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.First_name,new {#class = "form-control", name = "First_name" })
#Html.ValidationMessageFor(model => model.First_name)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Last_name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Last_name, new { #class = "form-control", name = "Last_name" })
#Html.ValidationMessageFor(model => model.Last_name)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date_of_birth, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Date_of_birth, null,new { #placeholder = "Date: MM-DD-yyyy",#class = "form-control", name = "Date_of_birth" })
#Html.ValidationMessageFor(model => model.Date_of_birth)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Student_id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Student_id, new { #class = "form-control", name = "Student_id" })
#Html.ValidationMessageFor(model => model.Student_id)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.City,new { #class = "form-control", id = "citySearch" , name = "City" })
#Html.ValidationMessageFor(model => model.City)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Description,8,1, new { #class = "form-control",name = "Description" })
#Html.ValidationMessageFor(model => model.Description)
</div>
</div>
<div class="form-group">
<div class="col-md-9 col-md-offset-3">
<div id="messages"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#studentForm').bootstrapValidator({
container: '#messages',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
First_name: {
validators: {
notEmpty: {
message: 'The first name is required and cannot be empty'
},
stringLength: {
max: 20,
min:2,
message: 'The full name must be between 2-20 characters'
},
regexp: {
regexp: /^[a-zA-Z\s]+$/i,
message: 'The full name can consist of alphabetical english characters and spaces only'
}
}
},
Last_name: {
validators: {
notEmpty: {
message: 'The last name is required and cannot be empty'
},
stringLength: {
max: 20,
min: 2,
message: 'The full name must be between 2-20 characters'
},
regexp: {
regexp: /^[a-zA-Z\s]+$/i,
message: 'The full name can consist of alphabetical english characters and spaces only'
}
}
},
Date_of_birth: {
validators: {
notEmpty: {
message: 'The birth date is required and cannot be empty'
},
date: {
message: 'The date is not valid',
format: 'MM-DD-YYYY'
}
}
},
Student_id: {
validators:{
notEmpty: {
message: 'The Student id is required and cannot be empty'
},
regexp: {
regexp: /^[0-9\b]+$/,
message: 'The student id should conatin only digits'
},
stringLength: {
max: 9,
min: 9,
message: 'The student id must be 9 digits'
}
}
},
Description: {
validators: {
stringLength: {
max: 1000,
message: 'The description field should be less than 1000 characters '
}
}
}
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#citySearch").autocomplete({
source: function(request,response) {
$.ajax({
url: "/Home/AutoCompleteCountry",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CityName,
value: item.CityName
};
}))
}
})
},
messages: {
noResults: "No Results was found",
results: function (resultCount) {
return resultCount + (resultCount > 1 ? ' results' : ' result ') + ' found';
}
}
});
})
</script>
and this is my model:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace StudentsManagment.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class student
{
public int Id { get; set; }
[Required(ErrorMessage ="First name field is required")]
[RegularExpression(#"^[a-zA-Z\s]+$")]
[Range(2, 20)]
public string First_name { get; set; }
[Required(ErrorMessage = "Last name field is required")]
[RegularExpression(#"^[a-zA-Z\s]+$")]
[Range(2, 20)]
public string Last_name { get; set; }
[Required(ErrorMessage = "Birth date field is required")]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
public System.DateTime Date_of_birth { get; set; }
[Required(ErrorMessage = "Student id field is required")]
[RegularExpression(#"^[0-9\b]+$")]
[StringLength(9)]
public string Student_id { get; set; }
public string City { get; set; }
[StringLength(1000)]
public string Description { get; set; }
}
}
the controller function is:
[HttpPost]
public ActionResult Create(student studentToCreate)
{
if (!ModelState.IsValid)
{
return View();
}
_db.students.Add(studentToCreate);
_db.SaveChanges();
return RedirectToAction("Index");
}
i found that the problem was in my _Layout.cshtml file for some reason when i removed those lines it didnt gave me the error:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
but now i am getting the following error after i click on create:
Remove simply RangeAttribute on those fields which must be used on numeric fields ;-)
If you want to control Length use the right one
MSDN - StringLengthAttribute
try to remove regular expression from firstname and LastName

Bootstrap Datepicker not displaying correctly

Hi Ive put in a bootstrap date picker on my asp.net mvc form.
Ive set it up so it starts displaying years from a decade.
But the date picker only displays the years as one longer string, its functional though
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
<script type="text/javascript">
$("#DateOfBirth").datepicker({
format: "dd/mm/yyyy",
startDate: "-120y",
endDate: "-10y",
startView: 2,
calendarWeeks: true,
defaultViewDate: { year: 1975, month: 01, day: 01 }
});
</script>
}
Helper in view
<div class="row">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { #class = "form-control", placeholder = "01/12/80" } })
#Html.ValidationMessageFor(model => model.DateOfBirth, "", new { #class = "text-danger" })
</div>
</div>
Thanks
What it should look like:
What it actually looks like:
As Jasen has pointed out i'd missed the css resource I'm the bundle config. Thanks

Resources