jQuery datepicker not displaying value from database - javascript

I have a field for inputting an employee's hire date that uses a jQuery datepicker, which works perfect. However, when you edit this employee's information the hire date field displays mm/dd/yyyy, but viewing the html shows the correct hire date value from the database. I implemented my datepicker using an editor template.
Generated HTML:
<input class="text-box single-line" data-val="true" data-val-date="The field Hire Date must be a date." data-val-required="The Hire Date field is required." id="HireDate" name="HireDate" type="date" value="02/12/89">
Editor Template:
#Html.TextBox("", Model.ToString("mm/dd/yyyy"), new { #class = "datepicker"})
View:
<div class="form-group">
#Html.LabelFor(model => model.HireDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HireDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HireDate, "", new { #class = "text-danger" })
</div>
</div>
JS:
$(document).ready(function () {
$(".datepicker").datepicker();
});
I have tried multiple variation of dateformat in the JS, but nothing seems to be working. What can I do to display the existing date?

Provided markup should show the value, there would be something else to understand.
The rendered HTML
<input class="text-box single-line"
data-val="true"
data-val-date="The field Hire Date must be a date."
data-val-required="The Hire Date field is required."
id="HireDate" name="HireDate"
type="date"
value="02/12/89"
/>
Here we can notice that the generated html for the element doesn't has css class = datepicker which we specify in view level(high precedence, supplied editor for css class will get override with view level class they cant merge together).
value="02/12/89" indicates that you've decorated with [DisplayFormat(DataFormatString="MM/dd/yy")] at Model Property HideDate
Now, it tells that control not rendering from its EditorTemplates view, it was rendering based on datatype with defaults as html5 input element with type=date and with placeholder as mm/dd/yyyy
Here we need to make sure that the naming conventions for EditorTemplates folder name and the view name.
Editor-Template View path would look like
..\Views\[Shared|ControllerName]\EditorTemplates\[DataType|CustomName].cshtml
Your Editor Template Path must be one of below two cases
In your case data-type = DateTime
So default view path would look like ..\Views\Shared\EditorTemplates\DateTime.cshtml
If your controller name is Employee the controller specific template path would be ..\Views\Employee\EditorTemplates\DateTime.cshtml
Your Case
If you're using custom name like Date.cshtml that you mentioned in comments then
path should be ..\Views\Shared\EditorTemplates\Date.cshtml
#model DateTime
#Html.TextBox("", Model.ToString("MM/dd/yyyy"), new { #class = "form-control datepicker" })
and from EditorFor you should pass view name like below
#Html.EditorFor(model => model.HireDate, "Date")

you must use the overload with format parameter
HtmlHelper.TextBox(string name, objeect value, string format, object htmlAttributes)
for examaple:
#Html.TextBox("", Model,"{0:dd/MM/yyyy}", new { #class = "datepicker"})

Related

Combo Box selected value to javascript

In my ASP.NET MVC web application, I send some data to the combo box using the view bag from the controller to the view.
In the view, there is a javascript when the combo box value is changed, I send that value to the controller again using an ajax call and get the related data, and show it in another textbox.
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName");
View
<div class="form-group row">
#Html.LabelFor(model => model.Task_Assigned_Branch_Id, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownList("Task_Assigned_Branch_Id", null, "Select the Branch", new { #class = "form-control js-dropdown js-Branch", #Id = "Branch" })
#Html.ValidationMessageFor(model => model.Task_Assigned_Branch_Id, "", new { #class = "text-danger" })
</div>
</div>
Javascript
$('.js-Branch').change(function () {
GetBranchMembers($(this).val())
});
This worked perfectly.
Then I want to change it, when sending the data to the view bag, I wanted to select a default value to the combo box and send it to the view.
So I changed the controller code to
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName", branchId);
Now the value is loading as the default selected value in the combo box.
So to get the combo box value in the loading event I wrote this
$(document).ready(function ()
{
var e = document.getElementById("js-Branch");
alert(e);
GetBranchMembers(e)
})
But the id returns null.
I guess because I sent the default value to the combo box, it doesn't pass the id to the script or something. Is there any other way of doing this?
Try using below code. i think you are using wrong id. you are using a class name in getElementbyId function
$(document).ready(function ()
{
var e = document.getElementById("Branch");
alert(e);
GetBranchMembers(e)
});

How to show dropdown list in the #Html.EditorFor() when user clicks on the text input box

I am passing data from the Controller to the View using the ViewData
Code in the controller:
public ActionResult Create()
{
ViewData["gN"] = new SelectList(db.gT, "id", "gN");
return View();
}
In the View I am using #Html.EditorFor() to create the new item for our table which we store in the database.
<div class="col-md-10">
#Html.EditorFor(model => model.gT.gN, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.groupid, "", new { #class = "text-danger" })
</div>
When I am using #Html.DropDownList our list of gN is perfectly showing as the dropdown list
#Html.DropDownList("gN", null, htmlAttributes: new { #class = "form-control" })
I want to use EditorFor() so that when the user starts typing in the input box, the dropdown list appears below it. and if that text which user is typing, present in the dropdown then the user can select it.
How we should show the list gN (which we are getting using ViewData from Controller) in the EditorFor() HTML element?
The Html.EditorFor() method always creates an <input> element, though the type attribute can vary depending on the model property type. HTML5 actually supports exactly what you want with the <datalist> element, which you tie to an <input> element with the list attribute. the <datalist> element takes child <option> elements containing the values you want in the list.
Making some guesses about your models here...
// Controller
public ActionResult Create()
{
ViewData["gN"] = db.gT;
return View();
}
// View
#Html.EditorFor(model => model.gT.gN, new { htmlAttributes = new { #class = "form-control", list="gN-datalist" } })
<datalist id="gn-datalist">
#foreach (var item in (gT)ViewData["gN"])
{
<option value="#item.id">#item.gN</option>
}
</datalist>
You could also create an HtmlHelper extension method that would create this for you.

mvc dropdownlistfor validation run before submitting

I have an MVC 5 Application. I have a View that inherits from a Model View. I have a DropDownlistFor with Validation that cannot be empty.
The problem I have is that Validation executes as soon as I select an item from Dropdownlist. When I select the same First item "Choose a Country", I mean, y select the same default option, validation execute and show a Message "Country is required"...
I put an alert on jquery Submit button and on Controller Method and it does not reach that point.
Another curious thing is that this App is a Migration from Entity Framework to Enterprise Library Store Procedure ..
The Model that inherits the View is loaded on the Controller from Store Procedure instead of EntityFrawork.
This should be transparent to the View. But this error happens only in this versiĆ³n. It Works fine with Entity Framework.
Here is part of the code..
#model AvivaVozSP.Models.UserViewModel
#using System.Web.Mvc.Ajax
<form action="#Url.Action("Create", "Users")" id="form" enctype="multipart/form-data" method="post">
<div class="DvCampoUp">
#Html.DropDownListFor(m => m.user.Country_id, Model.AvailableCountries, new { #class = "StyleOb Required txtFill", #onclick = "ocultar();", #onchange = "javascript:GetState(this.value);", #id = "Country_id" })
</div>
<div class="DvCampoUp">
#Html.ValidationMessageFor(model => model.user.Country_id, "", new { #class = "text-danger" })
</div>
</form>
<script language="javascript" type="text/javascript">
$('form').submit(function (event) {
alert(1);
});
Any Ideas?
Use the default value like this
<div class="DvCampoUp">
#Html.DropDownListFor(m => m.user.Country_id, Model.AvailableCountries,"Choose a Country", new { #class = "StyleOb Required txtFill", #onclick = "ocultar();", #onchange = "javascript:GetState(this.value);", #id = "Country_id" })
</div>
and remove Choose a Country from the list

Thousands separator with razor MVC and js

I'm trying to save number with thousands separator inside number field
1000 >> 1,000
100000 >> 10,000
2000.02 >> 2,000.02
i want to use js and jquery for this issue,
i want thousands separators become visible when the user is typing.
<div class="form-group">
<label class="control-label col-md-2" Sum</label>
<div class="col-md-10">
#Html.EditorFor(model => model.Sum, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(model => model.Sum, "", new { #class = "text-danger" })
</div>
</div>
Any help?
You can try autoNumeric plugin. Basic init will do what you need:
$('#Sum').autoNumeric('init');
Check section:
The basics on getting autoNumeric() up and running with the initialize
'init' method and default settings: ...

Updating DisplayFor Date with AJAX Result

In a view, there's a DisplayFor tied to a DateTime field in the Model. To update the field, an AJAX call returns a Date. I can convert the AJAX date into a MM/DD/YYYY value, but setting the DisplayFor with a .val doesn't update the view. Chrome Developer Tools shows no error, and in fact shows the correct converted DateTime, but the DisplayFor doesn't update. I haven't tried changing the .attr instead of the .val because it seems like .val would be the correct option. Can anyone see why the view isn't updating? Thanks in advance!
Model declaration:
DateTime? SaleDate { get; set; }
DisplayFor in View:
#Html.LabelFor(m => m.SaleDate, "Sale Date")
#Html.DisplayFor(m => m.SaleDate, "{0:d}", new { #class = "form-control" })
Update script inside successful AJAX call:
success: function (data) {
var $sDate = $("#SaleDate");
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(data[0].SaleDate);
var dt = new Date(parseFloat(results[1]));
$sDate.val(dt); //dt is correct Date, but DisplayFor isn't updating!
}
EDIT
The page source indicates that the id is correct, but there's no input. I assume this is because of a DisplayFor vs. a TextBoxFor, but could the apparent absence of an id be the problem?
<label for="SaleDate">Sale Date</label>
6/1/2016 12:00:00 AM//no input section, just the DateTime value
Or, if SaleDate is null:
<label for="SaleDate">Sale Date</label>
//no value or input section
The Razor code in the View produces some HTML code. Javascript works on client side and has no idea about Razor's #Html.DisplayFor, only about its output. I'm not strong in Razor so my offer can contain errors.
1. #Html.TextBoxFor(m => m.SaleDate, "{0:d}", new { #class = "form-control", id = "SaleDate" }).
JS remains the same. Con: This is editable textbox (input)
2. <span id="SaleDate" class="form-control">#Html.DisplayFor(m => m.SaleDate, "{0:d}")</span>
JS last line should be $sDate.html(dt);
I hope it helps.

Categories

Resources