MVC input DateTime - asp.net-mvc

If I use EditFor in MVC my DateTime field show a not formated datetime, If I use a old school html my field don't receive the error class.
<div class="editor-field">
<input type="text" name="EstimateTime" id="EstimateTime" value="<%: (Model != null) ? Model.EstimateTime.ToString("dd/MM/yyyy hh:mm:ss tt") : "" %>" />
<%: Html.TextBoxFor(model => model.EstimateTime, new { #value = (Model != null) ? Model.EstimateTime.ToString("dd/MM/yyyy hh:mm:ss tt") : "" })%>
<%: Html.ValidationMessageFor(model => model.EstimateTime) %>
</div>
result HTML: Look the difference between the value:
<div class="editor-field">
<input type="text" name="EstimateTime" id="EstimateTime" value="31/10/2013 01:54:42 PM" class="hasDatepicker">
<input id="EstimateTime" name="EstimateTime" type="text" value="10/31/2013 1:54:42 PM" class="input-validation-error text-box single-line">
<span class="field-validation-error">Isn't a date/time valid</span>
</div>
What is the best practices to fix it?

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
[DataType(DataType.Date)]
public System.DateTime EstimateTime { get; set; }
This is working for me in the latest version of Chrome

Add DataFormatString to the property in your model.
public class YourModel
{
[DisplayName("Estimate Time:"),
DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss tt}")]
public System.DateTime EstimateTime { get; set; }
...
}

I always use an Editor Template to perfect output control
this is DateTime.cshtml:
#model System.DateTime?
#{
IDictionary<string, object> Attributes = new Dictionary<string, object>();
if (ViewData.ContainsKey("style")) {
Attributes.Add("style", (string)ViewData["style"]);
}
if (ViewData.ContainsKey("autohelp")) {
Attributes.Add("title", (string)ViewData["autohelp"]);
}
if (ViewData.ContainsKey("autofocus")) {
Attributes.Add("autofocus", (string)ViewData["autofocus"]);
}
Attributes.Add("class", "fecha");
Attributes.Add("autocomplete", "off");
}
#Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), Attributes)

Related

Date DataAnnotation validation attribute not working - shows the time

Not working. Date comes back from a database field. Shows as:
When it is not set from a database as there is no birth date, I get a little red dot top left. Shows as:
I don't want the time included. I have a data annotation display format but it does not seem to take affect.
My Model(not showing other fields) is:
using System;
using System.ComponentModel.DataAnnotations;
namespace GbngWebClient.Models
{
public class UserProfileForMaintViewModel
{
// Can be null.
[Required]
[Display(Name = "Birth Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
[RegularExpression(#"(((0[1-9]|1[0-2])\/(0|1)[0-9]|2[0-9]|3[0-1])\/((19|20)\d\d))$", ErrorMessage = "Invalid date format.")]
public DateTime BirthDate { get; set; }
}
}
My view (not showing other fields) is:
#model GbngWebClient.Models.UserProfileForMaintViewModel
<h1 class="page-header">User Profile Maintenance</h1>
#{
ViewBag.Title = "UserProfileMaint";
Layout = "~/Views/Shared/_LayoutUser.cshtml";
}
#using (Html.BeginForm("UpdateUserProfile", "UserProfiler", FormMethod.Post))
{
<div style="margin-top:10px;"></div>
<div class="panel panel-default">
<div class="panel-heading">Your Profile</div>
<div class="panel-body">
<div class="row">
<div class="row">
<div class="col-md-3">
#Html.LabelFor(model => model.BirthDate, new { #class = "manadatory" })
#Html.TextBoxFor(model => model.BirthDate, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BirthDate, "", new { #class = "text-danger" })
</div>
<div class="col-md-3"></div>
</div>
<div style="margin-top:10px;"></div>
<div class="row">
<div class="form-group">
<div class="col-md-offset-0 col-md-12">
#* Submit button. *#
<input type="submit" value="Save" class="btn btn-info" />
</div>
</div>
</div>
</div>
</div>
}
From my previous experience I found out that it is much easier to deal with a string than a DateTime variable. So I usually use it as a hack. You can have an extra text field in your ViewModel and format it from the controller for the view -
public ActionResult Custom2()
{
var profile = new Profile();
profile.DoB = DateTime.Now.Date;
profile.DoBText = profile.DoB.ToString("yyyy-MM-dd");
return View(profile);
}
Now the view can accept the text data without any problem
#model mvcDeploymentTest.Models.Profile
#{
ViewBag.Title = "Custom2";
}
<h2>Custom2</h2>
#using (Html.BeginForm("PostTest", "Home", FormMethod.Post))
{
#Html.TextBoxFor(model => model.DoBText, new { #class = "form-control", Type = "date" })
<input type="submit" value="Submit" />
}
And once posted, you can parse the changed text value to datetime again with any formatting you want
[HttpPost]
public void PostTest(Profile myProfile)
{
DateTime dateValue;
if (!string.IsNullOrEmpty(myProfile.DoBText))
{
DateTime.TryParseExact(myProfile.DoBText,"yyyy-MM-dd", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateValue);
myProfile.DoB = dateValue;
}
return;
}
ApplyFormatInEditMode is only used/applied when using EditorFor - you have to use the overload for TextBoxFor which accepts a format string in order to get a formatted output in the rendered <input />.
#Html.TextBoxFor(model => model.BirthDate, "{0:d}", new { #class = "form-control" })
{0:d} will apply whatever short date format matches your app's culture settings. Replace that with a custom format string if you want something else.
If you want to use your browser's native date input (<input type="date" />), you'll need to use an ISO-8601 short date, which is YYYY-MM-DD. An example:
#Html.TextBoxFor(model => model.BirthDate, "{0:yyyy-MM-dd}", new { #class = "form-control", #type = "date" })
The default modelbinder knows how to transform that into a DateTime object, which you can then format into whatever else you wanted/needed.

DatePickerFor does not work

I am using telerik DatePickerFor for getting datetime value. Here is my model class:
public class Kisi
{
[Display(Name="date1")]
public DateTime date1{ get; set; }
[Display(Name = "date2")]
public DateTime date2 { get; set; }
[Display(Name = "date3")]
public DateTime date3{ get; set; }
}
Here is my view class:
//most parts ommited for brevity
#model LojmanMVC.Domain.Kisi
#{
ViewBag.Title = "KisiOlustur2";
}
<h2>KisiOlustur2</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<!-- date1-->
<div>
<div class="editor-label">
<label>date1? </label>
</div>
<div class="editor-field">
#(Html.Kendo().DatePickerFor(m=>m.date1)
.Name("dtpickerMemuriyetBaslama")
.Min(new DateTime(1900, 1, 1))
.Max(new DateTime(2099, 12, 31))
.Value(DateTime.Today)
)
<br />
<!-- Html.ValidationMessageFor(model => model.MemuriyetBaslamaTarihi)-->
</div>
</div>
<div id="tey" style="display:none">
<div class="editor-label">
#Html.LabelFor(model => model.date2)
</div>
<div class="editor-field">
#(Html.Kendo().DatePickerFor(m=>m.date2)
.Name("dtAskerlikBaslama")
.Min(new DateTime(1900, 1, 1))
.Max(new DateTime(2099, 12, 31))
.Value(DateTime.Today)
)
#Html.ValidationMessageFor(model => model.AskerlikBaslangicTarihi)
</div>
</div>
<div id="hey" style="display:none">
<div class="editor-label">
#Html.LabelFor(model => model.date3)
</div>
<div class="editor-field">
#(Html.Kendo().DatePickerFor(m=>m.AskerlikBitisTarihi)
.Name("dtAskerlikBitis")
.Min(new DateTime(1900, 1, 1))
.Max(new DateTime(2099, 12, 31))
.Value(DateTime.Today)
)
<p>
<input type="submit" value="Oluştur" />
</p>
</div>
</div>
And here is my controller :
public class KisiController : Controller
{
//
// GET: /Kisi/
public ActionResult Index()
{
return View();
}
public ActionResult KisiOlustur2()
{
Kisi kisi = new Kisi();
return View(kisi);
}
[HttpPost]
public ActionResult KisiOlustur2(Kisi sisi)
{
return View(sisi);
}
}
at sisi variable, date1,date2 and date3 is null, even though I entered them. How can I solve it? Thanks in advance.
Firstly, one thing I would suggest adding to your model, is the following:
[DataType(DataType.Date, ErrorMessage = "Please enter a valid date.")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name="date1")]
public DateTime date1{ get; set; }
You can customise the format string how you like and also your error message. This will ensure what the user enters has to actually be a date in the correct format.
However, I think your issue is that you are not actually passing the date from the view to the controller, you need to give your DatePickerFor a name and then pass this name into the controller for example:
[HttpPost]
public ActionResult KisiOlustur2(Kisi sisi, DateTime dtAskerlikBitis)
{
return View(sisi);
}

mvc getting and sending data from dropdown and datetimepicker

hello everyone I have a question. I have a form which consist of dropdown textbox and datetimepicker. I can fill my dropdown from my model but I cannot post the data to the database. Here are my codes
My Controller codes this is where the data selected and shown in view
public ActionResult orderProduct()
{
Repository<OrderProduct> _ro = new Repository<OrderProduct>();
IEnumerable<OrderProduct> _orderProduct = _ro.All().OrderByDescending(o => o.id);
return View(_orderProduct);
}
I am filling the dropdownlist from database
public ActionResult addOrderProduct()
{
/*
Repository<Workshop> _rw = new Repository<Workshop>();
IEnumerable<Workshop> _workshop = _rw.All().OrderByDescending(o => o.id);
IEnumerable<SelectListItem> _selectList = from w in _workshop
select new SelectListItem {
Text = w.name,
Value = w.id.ToString()
};
*/
Repository<Workshop> _rw = new Repository<Workshop>();
IEnumerable<SelectListItem> _workshopSelectListItem = _rw.All().AsEnumerable().Select(s =>
new SelectListItem {
Text = s.name, Value=s.id.ToString()
});
ViewData["dropdown"] = _workshopSelectListItem;
return View();
}
here I am trying to post my data to the database. I cannot select data from dropdown and datetimepicker also I cannot post this data by writing manually.
public ActionResult orderProductAdd(int adet, float cmt)
{
Repository<OrderProduct> _rp = new Repository<OrderProduct>();
OrderProduct _orderProduct = new OrderProduct { workshopId = 1, orderId = 1, value = adet, shipDate = new DateTime(2005, 02, 01), cmt = cmt };
return RedirectToAction("orderProduct");
}
this is my model
[Table("OrderProduct")]
public class OrderProduct
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public int orderId { get; set; }
[ForeignKey("orderId")]
public virtual Order order { get; set; }
public int workshopId { get; set; }
[ForeignKey("workshopId")]
public virtual Workshop workshop { get; set; }
public int value { get; set; }
public float cmt { get; set; }
public DateTime shipDate { get; set; }
/*
[id]
,[orderId]
,[workshopId]
,[value]
,[cmt]
,[shipDate]
*/
}
and also this is my view "addOrderProduct"
<form action="/Order/orderProductAdd" class="form-horizontal">
<div class="control-group">
<label class="control-label">Atölye Seçiniz</label>
<div class="controls">
#Html.DropDownList("dropdown",(IEnumerable<SelectListItem>)ViewData["dropdown"],"secim yapınız", new { #class = "span6 chosen" })
#*<select class="span6 chosen" data-placeholder="Choose a Category" tabindex="1">
<option value=""></option>
<option value="Category 1">A1</option>
<option value="Category 2">A2</option>
<option value="Category 3">A3</option>
<option value="Category 4">A4</option>
</select>*#
</div>
</div>
<div class="control-group">
<label class="control-label">Adet Giriniz</label>
<div class="controls">
<input type="text" class="span6 " name="adet" />
<span class="help-inline">Sadece sayı giriniz</span>
</div>
</div>
<div class="control-group last">
<label class="control-label">İhracat Tarihi</label>
<div class="controls">
<div id="ui_date_picker_inline"></div>
</div>
</div>
<div class="control-group">
<label class="control-label">Cmt</label>
<div class="controls">
<input type="text" class="span6 " name="cmt" />
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Onayla</button>
#*<button type="button" class="btn">Cancel</button>*#
</div>
</form>
How can I solve this ? Thank you.
The first argument in the DDL (below) is the assigned parameter being passed back to the server. When you call the action you're not passing the parameter dropdown. You're only calling int adet, float cmt but not a parameter called dropdown
#Html.DropDownList("dropdown",(IEnumerable<SelectListItem>)ViewData["dropdown"],
"secim yapınız", new { #class = "span6 chosen" })
So update your code to something like the one below:
public ActionResult orderProductAdd(int adet, float cmt, string dropdown){
// DO SOMETHING HERE
}
I can't see the input control which is being constructed for the DATETIME part of your query, however it will be similar to the above. Ensure the name of the INPUT matches the parameters being passed back to the server.

DataFormatString for DateTime

I'm trying to apply a format in a DateTime attribute but it is not working. I have this:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "dd/MM/yyyy", ApplyFormatInEditMode = true)]
public DateTime DataInscricao { get; set; }
I've tried to do it in many ways (changing the DataFormatString) but none of them are working. I'm also using datepicker for my Date fields.
I also tried to apply the format from jQuery:
$("#DataInscricao").datepicker( {dateFormat: 'dd-mm-yy'});
It almost works, the format is applied in the TextBox but when I try to Save the date format is lost. If I enter a date like 12/01/2013, it changes to 01/01/0001. In the GridView the format is different (mm-dd-yyyy) and the mask of the TextBox is working wrong.
I really don't know what to do to make it work. Is there someone who can help me with this issue?
Thanks!
UPDATE
This is the method in the Controller which returns the entity to edit.
public ActionResult Editar(int id)
{
var agendamento = _repository.GetSingle(a => a.Id == id);
return View("Criar", agendamento);
}
And this is the View:
#model PNCQ2013.Domain.Entities.AgendamentoManutencao
#{
ViewBag.Title = PNCQ2013.Domain.Resources.ItemPatrimonio.ItemPatrimonio.TitleAgendamento + " :: PNCQ - Programa Nacional de Controle de Qualidade";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="section">
#using (Ajax.BeginForm("Salvar", "ManutencaoPreventiva", null, new AjaxOptions { HttpMethod = "POST", LoadingElementId = "loading" }, new { #class = "formee", #id = "frmAgendamentoManutencao", enctype = "multipart/form-data" }))
{
#Html.HiddenFor(m => m.Id)
<div class="box">
<div class="title">
#PNCQ2013.Domain.Resources.ItemPatrimonio.ItemPatrimonio.TitleAgendamento
</div>
<div class="content nopadding">
<div class="grid-4-12">
#Html.LabelFor(m => m.ItemPatrimonioId)
#Html.DropDownListFor(m => m.ItemPatrimonioId, new SelectList(PNCQ2013.Web.Content.Helpers.Util.ListaItemPratrimonio().OrderBy(a => a.NumeroPatrimonio), "Id", "NumeroPatrimonio"), Resources.Geral.Selecione)
#Html.ValidationMessageFor(m => m.ItemPatrimonioId)
</div>
<div class="grid-4-12">
#Html.LabelFor(m => m.DataInscricao)
#Html.TextBoxFor(m => m.DataInscricao, new { #class = "datepicker" })
#Html.ValidationMessageFor(m => m.DataInscricao)
</div>
<div class="grid-4-12">
#Html.LabelFor(m => m.FrequenciaManutencaoId)
#Html.DropDownListFor(m => m.FrequenciaManutencaoId, PNCQ2013.Web.Content.Helpers.HtmlExtensions.ToSelectList(typeof(PNCQ2013.Domain.Enumerators.FrequenciaManutencao), ""), Resources.Geral.Selecione)
#Html.ValidationMessageFor(m => m.FrequenciaManutencaoId)
</div>
</div>
</div>
}
Try like this,
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DataInscricao { get; set; }

MVC3 EditorFor losing value on postback

I've created and date editorfor template but the value is getting lost on postback. Please can anyone help?
Here's my Date.cshtml stored in the 'shared/editortemplates' folder:
#model DateTime
<div class="input-append">
<input type="text" class="input-small datePicker" id="#ViewBag.Id" name="#ViewBag.Id" />
<span class="add-on"><i class="icon-th"></i></span>
</div>
Here's the view:
#Html.EditorFor(m => m.RequiredByDate, new { Id = "RequiredByDate" })
And the property on the viewmodel:
[Display(Name = "Required by date")]
[Required(ErrorMessage = "Required by date is required.")]
[DataType(DataType.Date)]
public DateTime RequiredByDate { get; set; }
Any help greatly appreciated.
I've not set the value on the input. what an idiot.
<input type="text" class="input-small datePicker" id="#ViewBag.Id" name="#ViewBag.Id" value="#Model.ToString("dd/MM/yyyy")" />

Resources