How to display a currency format in MVC - asp.net-mvc

In the model class, I am trying to display a currency format for the "Price" field, however the code I am using is not producing the desired result, and I have no idea why it is not working. I do not want to hard code the $ on every page, that would be a hassle. Here is the code I have in the model.
public partial class Item
{
public int ItemId { get; set; }
public string ItemDescription { get; set; }
public Nullable<int> Quantity { get; set; }
[DisplayName("Price Each")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
public string Price { get; set; }
[DisplayName("Due Date")]
[DisplayFormat(DataFormatString ="{0:d}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> DueDate { get; set; }
[DisplayName("Date Received")]
[DisplayFormat(DataFormatString= "{0:d}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> DateReceived { get; set; }
public string Comments { get; set; }
[DisplayName("W/O# or Cost Center")]
public int PurchaseID { get; set; }
public virtual PurchaseOrder PurchaseOrder { get; set; }
}
Thanks.

Wrong property type.
try:
public decimal Price { get; set; }

Related

ASP.NET date range constraint/validation

If I have a model that tracks employees request for holidays, how would I go about ensuring that an employee does not take multiple holidays within the same date range? Would this be handled with validation or creating a constraint in SQL Server? I used database first for this project.
public partial class HolidayRequestForm
{
public int RequestID { get; set; }
public int EmployeeID { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
public System.DateTime StartDate { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
public System.DateTime FinishDate { get; set; }
[Range(0.0001, int.MaxValue, ErrorMessage = "Hours Requested must be greater than zero. ")]
public decimal HoursTaken { get; set; }
public string Comments { get; set; }
public int YearCreated { get; set; }
public int MonthCreated { get; set; }
public int DayCreated { get; set; }
public Nullable<int> YearOfHoliday { get; set; }
[UIHint("Boolean.cshtml")]
public Nullable<bool> Approved { get; set; }
public string SubmittedBy { get; set; }
public string ApprovedBy { get; set; }
public virtual Employee Employee { get; set; }
}
Ideally I'd like that two employees can request the same date range but a single employee cannot request two holidays within the same date range. Could I use custom validation attribute maybe??
The given scenario is a business logic so it is better to implement this in your code itself instead of database constrains or triggers.
You can create a custom validator for the same and do a validation in the business layer. This approach will be easy maintainable/upgradable.
Use a normal method for validation , or create custom ValidationAttribute by inhering ValidationAttribute and by overriding IsValid method.

MVC Entity Framework Models and Relationships

im quite new to ASP.net and entity framework. I created a class but im just going to simplify it and take the example class from Microsoft. So here we go. These are all the example classes
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
public class Instructor
{
public int ID { get; set; }
[Required]
[Display(Name = "Last Name")]
[StringLength(50)]
public string LastName { get; set; }
[Required]
[Column("FirstName")]
[Display(Name = "First Name")]
[StringLength(50)]
public string FirstMidName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Hire Date")]
public DateTime HireDate { get; set; }
[Display(Name = "Full Name")]
public string FullName
{
get { return LastName + ", " + FirstMidName; }
}
public virtual ICollection<Course> Courses { get; set; }
public virtual OfficeAssignment OfficeAssignment { get; set; }
}
public class OfficeAssignment
{
[Key]
[ForeignKey("Instructor")]
public int InstructorID { get; set; }
[StringLength(50)]
[Display(Name = "Office Location")]
public string Location { get; set; }
public virtual Instructor Instructor { get; set; }
}
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "Number")]
public int CourseID { get; set; }
[StringLength(50, MinimumLength = 3)]
public string Title { get; set; }
[Range(0, 5)]
public int Credits { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public virtual ICollection<Instructor> Instructors { get; set; }
}
Like i said this is just for a example im trying to get know it.
My First Question: Do you need something like DepartmentID When you already do public virtual Department Department?
Second question: When i have a Collection of data how do i add values or Ids to that collection in the controller i can find this anywhere.
Third Question: Can some one link me a complete MVC example application with proper relationships

ASP.NET MVC4 Validation

I have a View model
public class TrainingProgramScheduledDateVM
{
public bool IsTuesday { get; set; }
[DataType(DataType.Time)]
public string TueStartTime { get; set; }
[DataType(DataType.Time)]
public string TueEndTime { get; set; }
public bool IsWednesday { get; set; }
[DataType(DataType.Time)]
public string WedStartTime { get; set; }
[DataType(DataType.Time)]
public string WedEndTime { get; set; }
public bool IsThursday { get; set; }
[DataType(DataType.Time)]
public string ThuStartTime { get; set; }
[DataType(DataType.Time)]
public string ThuEndTime { get; set; }
}
I want to put the validation i a way that.
1- If IsTuesday = true Then TueStartTime and TueEndTime should Requires.
and so on for other
2- At least one boolean value should be true and relevant time should be required.
please suggest me any easy way.
Thanks
Use remote validation. For example, Here
[Remote(
"doesProductNameExistUnderCategory",
"Northwind",
AdditionalFields = "Category_ID",
ErrorMessage = "Product name already exists under the chosen category. Please enter a different product name.",
HttpMethod = "POST"
)]
[Required]
public string Product_Name { get; set; }
I see repetition. This block:
public bool IsTuesday { get; set; }
[DataType(DataType.Time)]
public string TueStartTime { get; set; }
[DataType(DataType.Time)]
public string TueEndTime { get; set; }
Can better be abstracted into its own type, like:
public class ScheduleDate
{
public DayOfWeek DayOfWeek { get; set; }
public bool IsSelected { get; set; }
[DataType(DataType.Time)]
[RequiredIf(IsSelected)]
public string StartTime { get; set; }
[DataType(DataType.Time)]
[RequiredIf(IsSelected)]
public string EndTime { get; set; }
}
Then your TrainingProgramScheduledDateVM can contain a list of ScheduleDate objects.

AutoMapper and required fields

I am trying to create a new record using only some of the fields in my Domain Model. I have created a ViewModel for this and am using AutoMapper.
My code is failing at the minute due to the required fields that I have on my Domain Model. I have added opt=>opt.Ignore() on the necessary field however, I am still having problems.
When I remove [Required] from the StaffPresent field the record is added to the DB.
In my Global.asax.cs
Mapper.CreateMap<CustomerSupportRecord, CustomerSupportRecordForCreation>();
Mapper.CreateMap<CustomerSupportRecordForCreation, CustomerSupportRecord>().ForMember(p=>p.StaffPresent, opt=>opt.Ignore());
Domain Model
public class CustomerSupportRecord
{
public int CustomerSupportRecordID { get; set; }
[Required]
public int CustomerID { get; set; }
[Required]
public string EmployeeID { get; set; }
[Required(ErrorMessage = "Please enter a Date")]
[DataType(DataType.Date)]
[Display(Name = "Date")]
public DateTime Date { get; set; }
[Required(ErrorMessage = "Please select an Arrival Time")]
[DataType(DataType.Time)]
[Display(Name = "Arrival")]
public DateTime ArrivalTime { get; set; }
[DataType(DataType.Time)]
[Display(Name = "Departure")]
public DateTime? DepartureTime { get; set; }
[Required(ErrorMessage = "Please select a Type")]
[Display(Name = "Type")]
public int CustomerSupportTypeID { get; set; }
[Required(ErrorMessage = "Please enter the staff who were present at the Feedback")]
[Display(Name = "Staff Present at Feedback")]
public string StaffPresent { get; set; }
[Display(Name = "Setting")]
public string ReflectionSetting { get; set; }
[Display(Name = "Advisor")]
public string ReflectionAdvisor { get; set; }
[Display(Name = "Notes")]
public string Notes { get; set; }
[Display(Name = "Comments")]
public string Comments { get; set; }
// Navigation Properties
public virtual Customer Customer { get; set; }
public virtual CustomerSupportType CustomerSupportType { get; set; }
public virtual Employee Employee { get; set; }
}
ViewModel
public class CustomerSupportRecordForCreation
{
public int CustomerSupportRecordID { get; set; }
public int CustomerID { get; set; }
public string EmployeeID { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date")]
public DateTime Date { get; set; }
[DataType(DataType.Time)]
[Display(Name = "Arrival")]
public DateTime ArrivalTime { get; set; }
[Display(Name = "Type")]
public int CustomerSupportTypeID { get; set; }
[Display(Name = "Notes")]
public string Notes { get; set; }
}
And finally my Controller
//
// GET: /CustomerSupport/CustomerSupportRecord/Create
public ActionResult Create()
{
ViewBag.CustomerSupportTypeID = new SelectList(db.CustomerSupportType, "CustomerSupportTypeID", "CustomerSupportTypeName");
var model = new CustomerSupportRecordForCreation { CustomerID = 1, EmployeeID = "20213" };
return View("Create", model);
}
//
// POST: /CustomerSupport/CustomerSupportRecord/Create
[HttpPost]
public ActionResult Create(CustomerSupportRecordForCreation customersupportrecord)
{
if (ModelState.IsValid)
{
var newRecord = Mapper.Map<CustomerSupportRecordForCreation, CustomerSupportRecord>(customersupportrecord);
db.CustomerSupportRecord.Add(newRecord);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CustomerSupportTypeID = new SelectList(db.CustomerSupportType, "CustomerSupportTypeID", "CustomerSupportTypeName", customersupportrecord.CustomerSupportTypeID);
return View(customersupportrecord);
}
AutoMapper's configuration doesn't have anything to do with validation attributes, it just specifies the rules for how to map objects between each-other.
In your case, the mapping:
Mapper.CreateMap<CustomerSupportRecordForCreation, CustomerSupportRecord>().ForMember(p=>p.StaffPresent, opt=>opt.Ignore());
tells AutoMapper not to copy the StaffPresent property.
If your database model has a [Required] attribute, you'll still need to set that data elsewhere.
One thing to note based on your comment, it's a good idea to add validation to your ViewModels, as it prevents you from calling your database methods with improper data, gives you client side validation, and lets you enforce different constraints than your model might require.

One Model only update some fields in each view

I am wondering what is the correct way to approach this. I currently have one model - (shown below), which contains all the fields required for my record.
My issue is that when the record is created I only need to pass data for
CustomerID, EmployeeID, Date and ArrivalTime.
The remainder of the fields in the model will be populated when the record is updated at a later stage.
As some of my fields are required this will obviously cause validation errors if I don't post data for those fields.
I am wondering what is the best practice to achieve this?
Should I split the model into two?, or can I do partial validation?
public class CustomerSupportRecord
{
public int CustomerSupportRecordID { get; set; }
[Required]
public int CustomerID { get; set; }
[Required]
public string EmployeeID { get; set; }
[Required(ErrorMessage = "Please enter a Date")]
[DataType(DataType.Date)]
[Display(Name = "Date")]
public DateTime Date { get; set; }
[Required(ErrorMessage = "Please select an Arrival Time")]
[DataType(DataType.Time)]
[Display(Name = "Arrival")]
public DateTime ArrivalTime { get; set; }
[Required(ErrorMessage = "Please select a Departure Time")]
[DataType(DataType.Time)]
[Display(Name = "Departure")]
public DateTime DepartureTime { get; set; }
[Required(ErrorMessage = "Please select a Type")]
[Display(Name = "Type")]
public int CustomerSupportTypeID { get; set; }
[Display(Name = "Setting")]
public string ReflectionSetting { get; set; }
[Display(Name = "Advisor")]
public string ReflectionAdvisor { get; set; }
[Display(Name = "Notes")]
public string Notes { get; set; }
[Display(Name = "Comments")]
public string Comments { get; set; }
// Navigation Properties
public virtual Customer Customer { get; set; }
public virtual CustomerSupportType CustomerSupportType { get; set; }
public virtual Employee Employee { get; set; }
}
The correct approach would be to use different viewmodel classes for the different views and only include the properties you need on that view.
So your viewmodel for the first view look just like this:
public class CustomerSupportRecordForCreation
{
public int CustomerSupportRecordID { get; set; }
[Required]
public int CustomerID { get; set; }
[Required]
public string EmployeeID { get; set; }
[Required(ErrorMessage = "Please enter a Date")]
[DataType(DataType.Date)]
[Display(Name = "Date")]
public DateTime Date { get; set; }
[Required(ErrorMessage = "Please select an Arrival Time")]
[DataType(DataType.Time)]
[Display(Name = "Arrival")]
public DateTime ArrivalTime { get; set; }
}
You will have to map between that viewmodel classes and your domain/dal classes. This is where tools like AutoMapper comes in handy.
Edit Automapper:
Using Automapper is really simple.
You have to configure your mappings (i.e. in Application_Start). When the properties of the classes you want to map are named identically, its simple as this:
Mapper.CreateMap<CustomerSupportRecord,
CustomerSupportRecordForCreation>();
Then you can use the mapped in your app. When you have a CustomerSupportRecord and want to return the CustomerSupportRecordForCreation for your view write:
CustomerSupportRecord record = getRecordFromDb...
return View(Mapper.Map<CustomerSupportRecordForCreation>(record));
There is a good tutorial article on Codeproject: http://www.codeproject.com/Articles/61629/AutoMapper or just google

Resources