My datetime picker from my model is not working - asp.net-mvc-5

The dateTime picker is not showing in the view for me to select a date for my ReturnDate.It wont give me the little arrow to select from a calendar (datetime picker) and it already fills in values. It just shows a textbox that contains : '0001/01/01 12:00:00 AM'
in my model this is my Returndate field:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? ReturnedDate { get; set; }
my View is:
<div class="form-group">
#Html.LabelFor(model => model.ReturnedDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReturnedDate)
#Html.ValidationMessageFor(model => model.ReturnedDate)
</div>
</div>
using jquery ui this is my new view:
#model FCproject.Models.Purchase
#{
ViewBag.Title = "Create";
}
<script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<h4>Purchase</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.ReturnedDate, new { #class = "control-label col-md-2", #id = "datepicker" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReturnedDate)
#Html.ValidationMessageFor(model => model.ReturnedDate)
</div>
</div>
<script>
$(function () {
$("#datepicker").datepicker();
});
</script>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
But it still shows a textbox with no datetime picker.

if you are running on IE that feature doesn't work, chrome works the best on ui's.
But if still gives you problem i'll suggest you use jquery datepicker:
your View (Modified):
<div class="form-group">
#Html.LabelFor(model => model.ReturnedDate, new { #class ="control-label col-md-2", #id = "datepicker" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReturnedDate)
#Html.ValidationMessageFor(model => model.ReturnedDate)
</div>
</div>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
OR visit
http://api.jqueryui.com/datepicker/
Dont forget to reference your ui scripts e.g: (Depending on your script version)
<script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>

Related

MVC5 disable textbox based on another textbox value

I have a mvc5 project with ability to create;edit and delete records.
There are 3 textboxes.
Based on value in textBox1, I want to disable TextBox3 and 4;
if frequency.Value='Weekly'
{
Disable TextBox_BiWeekly
Enable TextBox3_Weekly
}
if frequency.Value='BiWeekly'
{
Disable TextBox3_Weekly
Enable TextBox4_BiWeekly
}
This is part of code in Edit.cshtml
<div class="form-group">
#Html.LabelFor(model => model.frequency, htmlAttributes: new { #class = ".col-form-label col-md-2" })
<div class="col-md-10">
<div class="form-check">
#Html.EditorFor(model =>model.frequency)
#Html.ValidationMessageFor(model =>model.frequency, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Weekly, htmlAttributes: new { #class = ".col-form-label col-md-2" })
<div class="col-md-10">
<div class="form-check">
#Html.EditorFor(model =>model.Weekly)
#Html.ValidationMessageFor(model =>model.Weekly, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BiWeekly, htmlAttributes: new { #class = ".col-form-label col-md-2" })
<div class="col-md-10">
<div class="form-check">
#Html.EditorFor(model =>model.BiWeekly)
#Html.ValidationMessageFor(model =>model.BiWeekly, "", new { #class = "text-danger" })
</div>
</div>
</div>
I am not sure how to disable or enable Textboxes
Thanks MR
Probably the best way to do this would be in JavaScript so that the textboxes can enable/disable on the fly based on the value of your frequency input.
Something like:
$(function() {
EnableDisableFrequency();
$('#Frequency').change(function() {
EnableDisableFrequency();
});
});
function EnableDisableFrequency() {
if ($('#Frequency').val() === "Weekly") {
$('#BiWeekly').prop('disabled', true);
$('#Weekly').prop('disabled', false);
} else if ($('#Frequency').val() === "BiWeekly") {
$('#BiWeekly').prop('disabled', false);
$('#Weekly').prop('disabled', true);
}
}
My JavaScript is a bit rusty but I'm pretty sure that should work.
I would however agree with Stephen Muecke that your Frequency input should be a dropdownlist.
#Html.DropDownListFor(m => m.Frequency, Model.FrequencyList)
Just define FrequencyList in your ViewModel as a List that contains all potential values which I assume is just Weekly and BiWeekly
FrequencyList = new List<SelectListItem>
{
new SelectListItem
{
Text = "Weekly",
Value = "Weekly"
},
new SelectListItem
{
Text = "BiWeekly",
Value = "BiWeekly"
}
};
The JavaScript can remain the same.

Required field validation not firing

I am building a MVC5 form and need to put validation for required fields. I am having several text controls that require to be validated. I tried putting the [Required] attribute on the model as well as added the required keyword in the htmlattributes on the client side but the validation never fires. Could somebody tell me how to handle this validation
<div class="form-group">
#Html.LabelFor(model => model.CustomerNumber, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
<div class="editor-field">
#Html.EditorFor(model => model.CustomerNumber, new { htmlAttributes = new { Value = Model.CustomerNumber == 0 ? "" : Model.CustomerNumber.ToString(), #class = "form-control", style = "width:100%", #readonly = "readonly", required = "required" } })
</div>
#Html.ValidationMessageFor(model => model.CustomerNumber, "", new { #class = "text-danger" })
</div>
</div>
add [Required] or other validator Attribute to your Model fields.
add jQuery Validate libs to your _Layout.cshtml file.
Example :
...
<body>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
</body>
</html>

Textboxes are different sizes

I created my controllers and views using scaffolded item but when I run my view in the program I can see that my textboxes are different sizes.How will I get it to all be the same size?
this is my view:
#model FCproject.Models.Purchase
#{
ViewBag.Title = "Edit2";
}
<h2>Edit2</h2>
#using (Html.BeginForm(new { OrderDate = Model.OrderDate }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Purchase</h4>
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.PurchaseID)
<div class="form-group">
#Html.LabelFor(model => model.CustomerID, "Customer Cell", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CustomerID", String.Empty)
#Html.ValidationMessageFor(model => model.CustomerID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DeliveryChoice, "DeliveryChoice", new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div>
<label>#Html.RadioButton("DeliveryChoice", true) Deliver my order to me</label>
</div>
<div>
<label>#Html.RadioButton("DeliveryChoice", false) I will pick up my order</label>
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderDueDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderDueDate)
#Html.ValidationMessageFor(model => model.OrderDueDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderTime, "Order Due Time", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderTime)
#Html.ValidationMessageFor(model => model.OrderTime)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderAdress1, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderAdress1)
#Html.ValidationMessageFor(model => model.OrderAdress1)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderAdress2, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderAdress2)
#Html.ValidationMessageFor(model => model.OrderAdress2)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderAdress3, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderAdress3)
#Html.ValidationMessageFor(model => model.OrderAdress3)
</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>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
here is a link to a picture of the screen as you can see it looks very messy because the textbox sizes are different, the 'Order Due Date' textbox is too thick the 'CustomerCell' textbox is too small, the 'Order Due Time' is too thick and short:
Edit screen link
The ASP.NET MVC project template uses bootstrap see (http://getbootstrap.com/)
for styling the HTML. The CSS file should be located at "Content\bootstrap.css".
Note that the view includes the following classes to style the form
<div class="form-horizontal">
<div class="form-group">
the submit button is styled using
<input type="submit" value="Save" class="btn btn-default" />
and some of the of the HtmlHelper Methods (such as LabelFor) contain code for additional styles that are added to the HTML.
For example
new { #class = "control-label col-md-2" }
in
#Html.LabelFor(model => model.CustomerID, "Customer Cell", new { #class = "control-label col-md-2" })
if you want to use bootstrap to style your form's controls, then you need to add the appropriate bootstrap CSS classes to the elements in the view.
Below are some examples (not related to your code) to style various elements with bootstrap.
To style a Drop-down list add,
Html.DropDownList("movieGenre", (SelectList)ViewBag.movieGenre, "All", new { #class = "form-control" })
this results in the following HTML with the class form-control:
<select class="form-control" id="movieGenre" name="movieGenre">
<option value="">All</option>
<option>Comedy</option>
<option>Western</option>
</select>
to style a textbox add
#Html.EditorFor(model => model.Genre, new { htmlAttributes = new { #class = "form-control" } })
to get output similar to
<input class="form-control text-box single-line" id="Genre" name="Genre" type="text" value="Comedy" />
you might also add the text-danger bootstrap CSS class to make the validation warning text red (or the color it's defined to be in the CSS file) like this:
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
To learn about bootstrap classes for form controls take a look at bootstrap's documentation.
To figure out where to place the new { #class = "form-control" } line in the HtmlHelpers take a look at its documentation (https://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper_methods(v=vs.118).aspx)
You can also add your own CSS file after bootstrap's CSS and style the elements (including width) by yourself, but if you use bootstrap this is not recommended.
Once you style the form elements with bootstrap, their width should be the same
(go to bootstrap's website and click on CSS then Forms for more information).

Model being passed in as null

When trying to add a new item to the database (using EF 6.1.3 and MVC 5) my model is always being passed in as null. Here's the model:
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace AccessorizeForLess.ViewModels
{
public class AddNewProductViewModel
{
public string Name { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
public decimal Price { get; set; }
public string AltText { get; set; }
public int Quantity { get; set; }
public string ImagePath { get; set; }
public HttpPostedFileBase Image { get; set; }
}
}
Here's the create method in the controller (I know it's convuluted but I'll work on that )
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include="ProductImageId,ProductName,ProductPrice,Quantity,ProductDescription")] AddNewProductViewModel model)
{
ProductImageViewModel image = new ProductImageViewModel() { ImagePath = "/Content/ProductImages/" + model.Image.FileName, AltText = model.AltText };
ProductImage newImage = new ProductImage() { ImagePath = image.ImagePath, AltText = image.AltText };
entities.ProductImages.Add(newImage);
await entities.SaveChangesAsync();
int ImageId = newImage.ProductImageId;
Product product = new Product()
{
ProductImageId = ImageId,
ProductName = model.Name,
ProductDescription = model.Description,
ProductPrice = model.Price,
Quantity = model.Quantity
};
string file = model.Image.FileName;
string path = #"/Content/ProductImages/";
model.Image.SaveAs(path + file);
if (ModelState.IsValid)
{
entities.Products.Add(product);
await entities.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.ProductImageId = new SelectList(entities.ProductImages, "ProductImageId", "ImagePath", product.ProductImageId);
return View("Index");
}
And the view:
#model AccessorizeForLess.ViewModels.AddNewProductViewModel
#{
ViewBag.Title = "Add New Product";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm("Create", "Products", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Product</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.ImagePath, "Image", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.ImagePath, new { #type = "file" })
#Html.ValidationMessageFor(model => model.ImagePath)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AltText, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AltText)
#Html.ValidationMessageFor(model => model.AltText)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Price, new { #class = "control-label col-md-2" ,#width = "25px"})
<div class="col-md-10">
#Html.EditorFor(model => model.Price)
#Html.ValidationMessageFor(model => model.Price)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Quantity)
#Html.ValidationMessageFor(model => model.Quantity)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { #cols = "25", #rows = "55" })
#Html.ValidationMessageFor(model => model.Description)
</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")
}
What am I doing wrong?
EDIT
#Stephen when I tried to run it again to answer your question I get this
And have no idea what this is, have you seen anything like this before?
EDIT
The error is
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1520: Method must have a return type
Source Error:
Line 641: #line default Line 642: #line hidden
Line 643:BeginContext("~/Views/Products/Create.cshtml", 2361, 9,
true); Line 644: Line 645:WriteLiteral("\r\n\r\n");
Source File: c:\Users\Richard\AppData\Local\Temp\Temporary ASP.NET
Files\vs\014a60c5\fc8be8b2\App_Web_create.cshtml.c6727781.vcyi-_hh.0.cs
Line: 643
EDIT
I have this for uploading the image:
string file = model.Image.FileName;
string path = Server.MapPath(#"~/Content/ProductImages");
model.Image.SaveAs(path + "/" + file);
I've stepped through it and all the variables are right, it adds the data to the database but doesn't save the image and I cannot for the life of me figure out why?
Replace:
public async Task<ActionResult> Create([Bind(Include="ProductImageId,ProductName,ProductPrice,Quantity,ProductDescription")] AddNewProductViewModel model)
with:
public async Task<ActionResult> Create([Bind(Include = "ImagePath,AltText,Name,Price,Quantity,Description")] AddNewProductViewModel model)

MVC 5 DataAnnotation Order Attribute

I Can't get the Display -> Order attribute to work.
I'm using VS2013 update 4 and the System.ComponentModel.DataAnnotations appears to be up to date with runtime version 4.0.30319.
I built a tiny MVC app with a small model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace TestDataAnnotation.Models
{
[MetadataType(typeof(TestDB))]
public class TestDB
{
public int TestDBID { get; set; }
[Display(Order=2)]
public int MyProperty1 { get; set; }
[Display(Order=1)]
public int MyProperty2 { get; set; }
}
}
I created a controller and view using scaffolding. The GET for the Create is standard MVC
// GET: TestDBs/Create
public ActionResult Create()
{
return View();
}
The View is also standard MVC:
<div class="form-horizontal">
<h4>TestDB</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.MyProperty1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MyProperty1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MyProperty1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MyProperty2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MyProperty2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MyProperty2, "", new { #class = "text-danger" })
</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>
}
MyProperty2 should display first, but it does not. I've tried numerous variations of this but can't get "Order" to work. I've had the MetadataType statement in the code and not in the code. I've tried order= -9. I've tried various different values for the order attribute. Display->Name works fine. Apparently, I'm missing some key idea here. Thanks for any and all help!
The Order parameter applies when there's something dynamic operating on the model and generating HTML, like a grid view. Here, you've literally rendered the properties in a given order. Setting Order isn't going to override explicit HTML.

Resources