Excluding properties from a viewmodel - asp.net-mvc

I have a viewmodel that contains a CustomerModel e.g.
public class MyAccountViewModel
{
public CustomerModel Customer { get; set; }
public LoginModel Login { get; set; }
public ICollection<AuthenticationClientData> Clients { get; set; }
public bool HasLocalPassword { get; set; }
public LocalPasswordModel Password { get; set; }
}
[DataContract]
public class CustomerModel
{
[DataMember]
public Guid CustomerBusinessId { get; set; }
[DataMember(IsRequired = true)]
[Required(ErrorMessage = "First Name is required")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[DataMember(IsRequired = true)]
[Required(ErrorMessage = "Last Name is required")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[DataMember]
public string FullName
{
get { return string.Format("{0} {1}", FirstName, LastName); }
}
[DataMember]
public string Identity { get; set; }
[DataMember(IsRequired = true)]
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; }
[DataMember]
[Display(Name = "Birth Date")]
public DateTime? BirthDate { get; set; }
[DataMember]
public string Mobile { get; set; }
[DataMember]
public string Phone { get; set; }
[DataMember]
public string Twitter { get; set; }
[DataMember]
[Display(Name = "Facebook")]
public string FaceBook { get; set; }
[DataMember]
public string WebSite { get; set; }
[DataMember]
public string Blog { get; set; }
}
My CustomerModel object contains a property "CustomerBusinessId" is it possible for my viewmodel to exclude this property so I am only returning the required fields to the view?

Related

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

Advice on datamodel structure

I'm practicing with ASP.Net MVC 5, and I'm attempting to build a prototype events directory. I've started with a basic layout, adapted from the Contoso University tutorial, but I want to start to develop a more complex data model, however I'm unsure as to the best way to develop the model, specifically, the different pricing options each listing can have.
My current data model is;
Vendors
public class Vendor
{
public int ID { get; set; }
[Required]
[Display(Name = "Company Name")]
[StringLength(50, ErrorMessage = "Company name cannot be longer than 50 characters.")]
public string CompanyName { get; set; }
[Required]
[Display(Name = "First Name")]
[StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
public string ContactFirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
[StringLength(50, ErrorMessage = "Last name cannot be longer than 50 characters.")]
public string ContactLastName { get; set; }
[Required]
[Display(Name = "Address")]
public string Address { get; set; }
[Required]
[Display(Name = "Address Line 2")]
public string AddressLine2 { get; set; }
[Required]
public string Region { get; set; }
[Required]
public string City { get; set; }
[Required]
public string Postcode { get; set; }
[Required]
[Display(Name = "Email Address")]
public string Email { get; set; }
[Required]
[Display(Name = "Phone Number")]
public string Phone { get; set; }
[Display(Name = "Twitter #username")]
public string TwitterHandle { get; set; }
[Display(Name = "Facebook URL")]
public string FacebookURL { get; set; }
[Required]
[Display(Name = "Active Vendor?")]
public Boolean ActiveStatus { get; set; }
public virtual ICollection<Listing> Listings { get; set; }
}
Listings
public class Listing
{
public int ListingID { get; set; }
public int CategoryID { get; set; }
public int VendorID { get; set; }
[Required]
[Display(Name = "Listing Name")]
public string ListingName { get; set; }
[Required]
[Display(Name = "Listing Description")]
public string ListingDesc { get; set; }
[Required]
[Display(Name = "Maximum Capacity")]
public int Capacity { get; set; }
[Required]
[DataType(DataType.Currency)]
[Display(Name = "Price Per Guest")]
public decimal PricePerGuest { get; set; }
[Required]
public string Address { get; set; }
[Display(Name = "Address Line 2")]
public string Address2 { get; set; }
[Required]
public string City { get; set; }
[Required]
public string Postcode { get; set; }
public virtual Category Category { get; set; }
public virtual Vendor Vendor { get; set; }
}
Categories
public class Category
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string CategoryDescription { get; set; }
public virtual ICollection<Listing> Listings { get; set; }
}
Ideally, I'd like to add to the Listing table a new property called 'Fixed Price', giving vendors the option to either list by price per guest or by fixed price, as not all vendors can price their services by price per guest.
Is a separate table with pricing options sufficient enough to develop this further?
P.S - I haven't yet started to format the entities properly yet, hence why categories is missing validation and so on.
Price (currency) and IsFixedPrice (bit) Instead of PricePerGuest
Thanks to #Nikhil Vartak for the answer

Ideal model structure for an ASP.NET MVC project for handeling multiple partial views

I have two partial views named as _centerDetails.cshtml and _centerRights.cshtml .
I am passing data from centerdetails when I click on submit and want to show this when another partial view is switched, but without posting it to the server.
This is my model class which I have created to handling my data via
controller:
namespace ADWP_AdminWebPortal.Models
{
public class CountryList
{
[Required(ErrorMessage = "Select a Country.")]
public int CountryId { get; set; }
[Required]
public string Country { get; set; }
[Required(ErrorMessage = "Select a State.")]
public int StateId { get; set; }
[Required]
public string State { get; set; }
[Required(ErrorMessage = "Select a City.")]
public int CityId { get; set; }
[Required]
public string City { get; set; }
}
public class CustomerDetails: CountryList
{
public int ClientId { get; set; }
[Required (ErrorMessage="Eneter the First name")]
[DataType(DataType.Text)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Eneter the Middle name")]
[DataType(DataType.Text)]
public string MiddleName { get; set;}
public string NatureOfOccupation { get; set; }
public string AgentId { get; set; }
[Required(ErrorMessage ="Select a Client Type.")]
public string ClientType { get; set; }
public int TariffId { get; set; }
public string TariffName { get; set; }
public int ServiceId { get; set; }
public string ServiceName { get; set; }
public string OrderId { get; set; }
public int PaymentMethodId { get; set; }
public string PaymentMethodName { get; set; }
}
}
Here you can see the mess I have created. My problem is how to handle multiple models when you are working with multiple models in same controller?
Here I did not created all the data in a single class because I wanted it to reuse as per my need.
How can I handling data in a model? This is the main problem that is
coming to me while I am creating the partial views in my project.
You may use CTE and ROW_NUMBER function together to delete duplicate rows from your table.
With CTE AS (
SELECT VERIFICATIONTYPE,
NAME,
COST,
RN = ROW_NUMBER() OVER (PARTITION BY VERIFICATIONTYPE, NAME, COST ORDER BY VERFICATIONTYPE)
FROM DETAILS)
DELETE FROM CTE WHERE RN > 1
END
After a bit of a struggle I got the result.
public class CountryList
{
[Required(ErrorMessage = "Select a Country.")]
public int CountryId { get; set; }
[Required]
public string Country { get; set; }
}
// Added Class
public class State
{
[Required(ErrorMessage = "Select a State.")]
public int StateId { get; set; }
[Required]
public string State { get; set; }
}
// Added Class
public class City
{
[Required(ErrorMessage = "Select a City.")]
public int CityId { get; set; }
[Required]
public string City { get; set; }
}
public class CustomerDetails
{
public int ClientId { get; set; }
[Required (ErrorMessage="Enter the first name")]
[DataType(DataType.Text)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Enter the middle name")]
[DataType(DataType.Text)]
public string MiddleName { get; set; }
public int TariffId { get; set; }
public string TariffName { get; set; }
public int ServiceId { get; set; }
public string ServiceName { get; set; }
public string OrderId { get; set; }
public int PaymentMethodId { get; set; }
public string PaymentMethodName { get; set; }
public List<CountryList> { get; set; } //added list
public List<State> { get; set; } //added list
public List<City> { get; set; } //added list
}
Yeah, it was so easy.

Validate a field in a model against a field in a referenced model

I have a model that references another model and I'd like to validate using data from the referenced model. Is this possible?
Here's my model:
namespace PHAMVC.Models {
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using ExpressiveAnnotations.Attributes;
[Table("Address")]
public partial class Address {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AddressID { get; set; }
public int PHAMemberID { get; set; }
[Display(Name = "Address Type (Home/Mailing/Other)")]
public int AddressTypeID { get; set; }
[Required]
[StringLength(60)]
[Display(Name = "Street")]
public string AddressLine1 { get; set; }
[StringLength(60)]
[Display(Name = " ")]
public string AddressLine2 { get; set; }
public int ZipCodeID { get; set; }
[AssertThat("(AddressTypeID == 1 && DistrictID != 0) || (AddressTypeID != 1)", ErrorMessage = "School District MUST be identified for your Home Address.")]
[Display(Name = "School District Name")]
public int DistrictID { get; set; }
public virtual AddressType AddressType { get; set; }
public virtual District District { get; set; }
public virtual ZipCode ZipCode { get; set; }
}
}
And here is the District model:
namespace PHAMVC.Models {
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("District")]
public partial class District {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public District() {
Addresses = new HashSet<Address>();
}
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "School District Name")]
public int DistrictID { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "School District Name")]
public string DistrictName { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[StringLength(4)]
public string DistrictCode { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int? CountyNumber { get; set; }
public long? NCESDistrictID { get; set; }
[Required]
[StringLength(50)]
public string CountyName { get; set; }
[Required]
[StringLength(60)]
public string StreetAddress { get; set; }
[Required]
[StringLength(50)]
public string City { get; set; }
[Required]
[StringLength(2)]
public string StateCode { get; set; }
[StringLength(15)]
public string Phone { get; set; }
[StringLength(2)]
public string LocaleCode { get; set; }
[StringLength(25)]
public string Locale { get; set; }
public double? StudentTeacherRatio { get; set; }
public int? Students { get; set; }
public int? Teachers { get; set; }
public int? Schools { get; set; }
public int ZIP { get; set; }
public int? ZIPPlus4 { get; set; }
[StringLength(25)]
public string DistrictType { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public bool? isRegularDistrict { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public bool? isRegionalDistrict { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public bool? isStateDistrict { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public bool? isSCCounty { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[StringLength(100)]
public string DisplayName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Address> Addresses { get; set; }
}
}
What I'm trying to do in the Address Model, conceptually is this:
[AssertThat("ZipCodeID == District.ZIP")]
public int DistrictID { get; set; }
It seems reasonable since the District model is referenced in the Address model, but it produces this exception:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: ExpressiveAnnotations.Analysis.ParseErrorException: Parse error on line 1, column 22:
... ZIP ...
^--- Only public properties, constants and enums are accepted. Identifier 'ZIP' not known.
Am I missing some obvious way to make District.Zip PUBLIC in the Address model?
I'm really new to this, so any guidance or help would be greatly appreciated!

Save data finally after all action completed

hi please help me I have 5 model and I want to save all model at once so please help me
my models are
public partial class EmployeeMainTable
{
public EmployeeMainTable()
{
this.employee_DepartmentTable = new List<EmployeeDepartmentTable>();
}
public int EmployeeId { get; set; }
[Required(ErrorMessage = "Enter the Name")]
public string EmployeeName { get; set; }
[Required(ErrorMessage = "Enter date of joining")]
[DataType(DataType.Date)]
public System.DateTime EmployeeDateOfJoining { get; set; }
[Required(ErrorMessage = "Department Required")]
public int EmployeeDepartmentId { get; set; }
[Required(ErrorMessage = "Designation Required")]
public int EmployeeDesignationId { get; set; }
[Required(ErrorMessage = "Location Required")]
public int EmployeeLocationId { get; set; }
[Required(ErrorMessage = "Employee status Required")]
public int EmployeeStatusId { get; set; }
[Required(ErrorMessage = "Employee Type Required")]
public int EmployeeTypeId { get; set; }
[Required]
public bool EmployeeIsActive { get; set; }
[Required(ErrorMessage = "Confirmed Date Required")]
[DataType(DataType.Date)]
public DateTime EmployeeConfirmDate { get; set; }
[Required(ErrorMessage = " Email required")]
[RegularExpression(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = " Must be a valid e-mail address ")]
public string EmployeeEmailId { get; set; }
[Required(ErrorMessage = "Contact Number Required")]
public string EmployeeContactNumber { get; set; }
[Required(ErrorMessage = "Date of Birth Required")]
[DataType(DataType.Date)]
public DateTime EmployeeDateOfBirth { get; set; }
public ICollection<EmployeeAssetsTable> employee_AssetsTable { get; set; }
public List<EmployeeDepartmentTable> employee_DepartmentTable { get; set; }
public ICollection<EmployeeDesignationTable> employee_DesignationTable { get; set; }
public ICollection<EmployeeEducationDetailTable> employee_EducationTable { get; set; }
public ICollection<EmployeeFamilyTable> employee_FamilyTable { get; set; }
public ICollection<EmployeeLocationTable> employee_LocationTable { get; set; }
public ICollection<EmployeeStatusTable> employee_StatusTable { get; set; }
public ICollection<EmployeeTypeTable> employee_TypeTable { get; set; }
public virtual ICollection<EmployeePreviousCompanyDetailTable> employee_PreviousCompanyDetailTable { get; set; }
public virtual ICollection<EmployeeDocumentsTable> employee_DocumentTable { get; set; }
likewise I have 5 models
what I need I need to pas model from action to action and if I click submit button in last section data get saved from all model at once
If I understand correctly, can't you just have a property in model #2 for model#1, a property for model #2 and #1 in model #3, and so forth..
Or use custom ViewModels that's served to fit your purpose.
I just started with MVC so this is my novice advice, don't take it for granted.

Resources