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.
Related
In my Create view, there is a Date picker to select the date for the user.
Then the edit view, I want to pass the same date values to the edit view.
This is my view property looks like
#Html.EditorFor(model => model.Date_of_birth, new { htmlAttributes = new { #class = "form-control js-datepicker", Type = "Date" } })
It shows the date picker, but not shows the passed date value.
You should fill the model at action in that controller which you returning Edit view then #Html.EditorFor(model => model.Date_of_birth, new { htmlAttributes = new { #class = "form-control js-datepicker", Type = "Date" } })
will fill the data for you.
I removed the time selection in the calendar widget and the start date in the fields also without time.
But the main problem is that when you select a date, the current time is still inserted in the field. Need only to display the date, without the time.
cshtml
<div class="form-group">
#Html.LabelFor(model => model.DateTo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateTo, "{0:d}", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateTo, "", new { #class = "text-danger" })
</div>
js
$("#DateTo").datetimepicker({
timepicker: false,
pickTime: false,
closeOnDateSelect: true,
dateFormat: "yy/mm/dd"
});
Model
[Display(Name = "DateTo", ResourceType = typeof(Resources.Resource))]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
[Required]
public DateTime DateTo { get; set; }
jQuery DateTimePicker plugin v2.4.5
If there are simple alternative widgets for asp net, please advise.
To display only the date without the time, just do it this way:
$("#DateTo").datepicker({
dateFormat: "yy/mm/dd",
closeOnDateSelect: true
});
Because you're going through .datetimepicker where it picks up date and time, .datepicker picks up only thedate.
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.
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.
I have one big doubt. I have "Customer Form". Customer Form contain 22 fields. I have Db for "Customer Form". it Contain"Multiple tables" with "many to many relationship". If I connect my Db with "Vb express 2012" using "Connection Strings" and also created EDMX file.it shows view for each table. so i tried to bring all fields in "Single view" and tried to insert the data into multiple tables. For that I used "Code First Approach" i followed the method same as like which is mentioned in the below link. Its working Fine.
http://www.codeproject.com/Tips/651495/Inserting-Data-into-Multiple-Tables-using-Code-Fir
Now my question is i finished the "insert" process using Code first approach.. Now " how to do UPDATE process using this approach.. Because i did only the insertion process . still i need to do Update , Details, Delete.. How to do that?
Thanks.
add your customers in a foreach lop in a view and pass each ones primary key to the edit and delete methods of the controller as follows:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.s1)
</td>
<td>
#Html.DisplayFor(modelItem => item.s2)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.id })
</td>
</tr>
}
then in your controller make a GET method to accept the primary key as a parameter from the view as follows:
public ActionResult Edit(int id)
{
Class1 class1 = db.Class1.Find(id);
return View(class1);
}
and then make a Form in your Edit View to POST back the values as:
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>Class1</h4>
<hr />
#Html.HiddenFor(model => model.id)
<div class="form-group">
#Html.LabelFor(model => model.s1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.s1, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.s2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.s2, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
then in your controller make a POST method to accept the model as a parameter from the view as follows:
[HttpPost]
public ActionResult Edit([Bind(Include = "id,s1,s2")] Class1 class1)
{
db.Entry(class1).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
Similarly make GET and POST methods for Delete.
basically in an update method...
Find the object to be updated
-Example your datacontext class object=ctx,tablename=details
update the found object with the new data
if you're not passing an entire object to the method then just pass the primary key of the object to be updated and the new values
public void update(details newData)
{
var result=ctx.details.Find(id);
result.name=newData.Name;
result.age=newData.Age;
ctx.SaveChanges();
}
to Delete:
a similar process
Find the object -Example your datacontext class object=ctx,tablename=details
Remove it
public void Delete(int id)
{
var result=ctx.details.Find(id);
ctx.details.Remove(result);
ctx.SaveChanges();
}