In my final ASP.NET assignment, I am instructed to use a code first approach and add the following properties and Model(s) to represent the described changes.
1) A Person 'has a' Address object (This class was given, but I modified adding properties)
2) An Address object has a single property of type string for Email. (I created this class)
namespace ContosoUniversity.Models
{
public class Address
{
[Required]
[RegularExpression(#"[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z] {2,4}")]
public string Email { get; set; }
[Required]
[Compare("Email")]
public string EmailConfirm { get; set; }
}
}
but now I am not sure what he means in the first instruction. I have researched composition, inheritance, and abstract classes but still don't know what I am suppose to do?
How am I suppose to create an Address object in the person class? What does that actually mean? Here is the Person class:
namespace ContosoUniversity.Models
{
public abstract class Person
{
public int ID { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
[Column("FirstName")]
[Display(Name = "First Name")]
public string FirstMidName { get; set; }
[Display(Name = "Full Name")]
public string FullName
{
get
{
return LastName + ", " + FirstMidName;
}
}
}
}
It means that there should be a one to one relationship between the person and an address. A Person has one Address.
namespace ContosoUniversity.Models
{
public abstract class Person
{
public int ID { get; set; }
public Address Address {get; set;}
[Required]
[StringLength(50)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
[Column("FirstName")]
[Display(Name = "First Name")]
public string FirstMidName { get; set; }
[Display(Name = "Full Name")]
public string FullName
{
get
{
return LastName + ", " + FirstMidName;
}
}
}
}
Now you can do something like this (assuming Person wasn't an abstract class)...
Person person = new Person();
person.Address = new Address();
person.Address.Email = "john.doe#example.com";
If your teacher had said something like "a person can have multiple addresses" you could have done something like this (omitted duplicate lines for brevity):
public class Person
{
public IEnumerable<Address> Addresses {get; set;}
public Person()
{
Addresses = new List<Address>(); //initialize with an empty collection
}
}
which would allow you to do this...
Person john = new Person();
Address home = new Address(){Email = "john.doe#example.com"}; //create a new address and set its Email property to a value in a single line
Address work = new Address(){Email = "johndoe#work.com"};
john.Addresses.Add(home); //Add the address to the Addresses collection of john
john.Addresses.Add(work);
Related
I have two classes - parent and child.
This is the parent class
[Table("tbl_Parent")]
public partial class Parent
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
[ScaffoldColumn(false)]
public int Parent_Id { get; set; }
[Required(ErrorMessage = "you must provide parent First Name")]
[Display(Name = "Full Name")]
public string Parent_Full_Name{ get; set; }
[Required(ErrorMessage = "you must provide parent Email Address")]
[Display(Name = "Email Address")]
[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessage = "Correct Input")]
[StringLength(100, ErrorMessage = "at least 10 Char", MinimumLength = 10)]
public string Parent_Email { get; set; }
[Required(ErrorMessage = "you must provide parent phone number")]
[Display(Name = "Phone Number")]
[DataType(DataType.PhoneNumber)]
public int Parent_Phone { get; set; }
[Required(ErrorMessage = "you must provide parent password")]
[Display(Name = "Password")]
[DataType(DataType.Password)]
public string Parent_Password { get; set; }
public string Parent_Location { get; set; }
[Required(ErrorMessage = "you must provide parent status")]
[Display(Name = "Parent status")]
public string Parent_status { get; set; }
public string Par_User_Type { get; set; }
public ICollection<Child> child { get; set; }
}
and this is the child class
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Chi_Id { get; set; }
[Required(ErrorMessage ="you must provide child first name")]
[Display(Name ="Child First Name")]
public string Chi_First_Name { get; set; }
[Required(ErrorMessage ="you must provide child last Name")]
[Display(Name ="Child Last Name")]
public string Chi_Last_Name { get; set; }
[Required(ErrorMessage ="you must provide child age")]
[Display(Name ="Child Age")]
[Range(0,18, ErrorMessage = "Correct Input")]
public int Age { get; set; }
[Required(ErrorMessage ="you must provide child gender")]
[Display(Name ="Child Gender")]
public string Gender { get; set; }
[Display(Name ="Child School")]
public string Chi_School { get; set; }
[Required(ErrorMessage ="you must provide parent status")]
[Display(Name ="Child Parent Status")]
public string Chi_parent_status { get; set; }
[Display(Name ="Child Image Path")]
public string Chi_Image_Path { get; set; }
public virtual Admin admin { get; set; }
public int Adm_ID { get; set; }
public virtual Parent parent { get; set; }
public int Par_ID { get; set; }
}
The parent class can have many children.
I want add id of child in parent class across controller. This is my controller:
[HttpGet]
public ActionResult Rigester()
{
if (Session["ID"] == null)
{
return RedirectToAction("Login", "Home");
}
return View();
}
[HttpPost]
public ActionResult Rigester(Parent parent,int id)
{
if (ModelState.IsValid)
{
using (Context db = new Context())
{
var child1 = db.child.Where(x => x.Chi_Id == id).First();
parent.Par_User_Type = "Parent";
parent.child.Add(child1);
db.parent.Add(parent);
db.SaveChanges();
return RedirectToAction("Home", "Admin");
}
}
return View();
}
In the controller, I get an error when executing this code:
Null reference exception
on this line of code:
parent.child.Add(child1);
The end of each class has relationship between another class.
How can I add child when register new parent?
Instead of adding via navigation properties, in your controller you could assign the ParentId as foreign key for the child.
In the code below, first we added parent to the database, then we assigned the parentId in the child object.
[HttpPost]
public ActionResult Rigester(Parent parent,int id)
{
if (ModelState.IsValid)
{
using (Context db = new Context())
{
parent.Par_User_Type = "Parent";
db.parent.Add(parent);
db.SaveChanges();
var child1 = db.child.Where(x => x.Chi_Id == id).First();
child1.Par_Id = parent.Parent_Id;
db.SaveChanges();
return RedirectToAction("Home", "Admin");
}
}
return View();
}
Hi I have 2 table name tblGroup and tblSubGroup and tblGroup has GroupId which is primary and tblSubGroup has Groupid which is foreign key.
Below are the model generated for them
tblGroup Model
public partial class tblGroup
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public tblGroup()
{
this.tblSubGroups = new HashSet<tblSubGroup>();
}
public int GroupID { get; set; }
[Required(ErrorMessage = "Group Name is Required")]
public string Title { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<tblSubGroup> tblSubGroups { get; set; }
}
tblSubGroup Model
public partial class tblSubGroup
{
public int SubGroupID { get; set; }
[Display(Name = "tblGroup")]
public int GroupID { get; set; }
[Required(ErrorMessage = "SubGroup Name is Required")]
public string Title { get; set; }
public virtual tblGroup tblGroup { get; set; }
}
Now on deleting record of From GroupTable it is giving issue. Instead I need to validate a message that "This record is bind with another table or entity. So it cannot be deleted". I need to show this kind of message.
As I am new I don't know this things is possible or not
Since you need to verify with the database you move this type of validation to the server.
[HttpPost]
public ActionResult Delete(Group group)
{
var grp = db.Group.FirstOrDefault(g => g.Id == group.Id);
if (HasSubGroups(grp))
{
ModelState.AddError("DeleteValidation", "Cannot delete while sub-groups exists");
return View(group);
}
// delete normally ...
}
Then you could display the errors on the view in several ways. The simplest is just to show the collection.
#Html.ValidationSummary()
I have two models Invoice and Client which has one to many relation. My problem is when I try to create a new invoice the modelstate becomes false because the required fields of the Client object are not filled. I tried to set default values e.g. int property {get; set;} = 1; but this causes to override the property value when I try to retrieve the relational model. I'm new to asp.net any help would be appreciated.
Here is my Client model code:
public class Client
{
public int ClientId { get; set; }//Primary key
[Required]
[Display(Name = "Client/Company Name")]
public string Name { get; set; }
//.....
public List<Invoice> Invoices { get; set; }
}
Invoice Model:
public class Invoice
{
public int InvoiceId { get; set; }//Primary key
[Required]
[Display(Name = "Client/Company Name")]
public int ClientId { get; set; }//Foreign key
public Client client { get; set; }
//....
}
My code to save an invoice:
[HttpPost]//Save quote & redirect to edit quote
public IActionResult Create(Invoice quote)
{
ViewData["Title"] = "Create Quotation";//Set title of the view!
if (ModelState.IsValid)//If quote is validated to true.
{
_context.Invoices.Add(quote);//insert quote
_context.SaveChanges();
//Redirect to edit page to add items to the invoice
return RedirectToAction("Edit", new { id = quote.InvoiceId });
}
//...
}
My code to retrieve invoices with their client names
public IActionResult Index()
{
ViewData["Title"] = "Quotations";//Set title of the view!
//Return with array of all quotations.
return View(_context.Invoices.Include(i => i.client).Where(i => i.isQuote == true).ToArray());
}
Any hints or help would be appreciated.
Found a simpler solution:
Just add virtual keyword and GG
in Invoice Model:
public class Invoice
{
public int InvoiceId { get; set; }//Primary key
[Required]
[Display(Name = "Client/Company Name")]
public int ClientId { get; set; }//Foreign key
public virtual Client client { get; set; }
//....
}
I am having a problem uploading images in ASP.NET MVC 3. Currently I have a class called EmployeeModel which has the properties for employees:
public class EmployeeModel //Model for employee information
{
[Required(ErrorMessage = "ID Required")]
public int ID { get; set; }//Employee Id
[Required(ErrorMessage = "Name Required")]
[RegularExpression(#"^[a-zA-Z\s]+$", ErrorMessage = "Name can have only alphabets and spaces")]
public string Name { get; set; }//Employee Name
[DataType(DataType.Date)]
public DateTime DOB { get; set; }//Employee Date of birth
[DataType(DataType.Date)]
public DateTime DOJ { get; set; }//Employee Date of Joining
[Required(ErrorMessage = "Address Requried")]
public string Address { get; set; }//Employee Address
[Required(ErrorMessage="Mobile Number Requried")]
[RegularExpression(#"[0-9]{10}", ErrorMessage = "Mobile number not valid")]
public double Mobile { get; set; }//Employee Mobile number
[Required(ErrorMessage = "Email Requried")]
[RegularExpression(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Email Id not valid")]
public string Email { get; set; }//Employee Email-ID
[Required(ErrorMessage = "Designation Requried")]
public string Designation { get; set; }//Employee Designation
[Required(ErrorMessage = "Salary Required")]
public double Salary { get; set; }//Employee Salary
}
The requirement is that I need to upload an image for each employee and display them. I'm using a text file to store the information of the employee (acting as a database).
Maybe these articles can help: this and this.
The one from CodeProject uses MongoDB, but I think you can ignore that parts and get what you want. It seems simple enough.
And this one is the most simple one from SO.
Try to use HttpPostedFileBase property in your model.
And in your POST action use :
#using (Html.BeginForm("Action_name", "Controler_name", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
// your form data here
}
I'm working with ASP.NET MVC4.
I am looking to change the display name of a property based on some other value retrieved from a database, so that when I call #Html.LabelFor() in my view, the correct field text is displayed.
The example I'm working with uses an Address View Model, with different properties for each line of the address. If the address is US, then one of the fields should say 'State'. If it's a UK address, it should say 'County'. Same applied for 'Zip Code' and 'Post Code'.
Obviously I don't want different Properties for each different field for each country.
I also what to apply a different regular expression validation rule for the Postal Code depending on the country. How can I also do this?
Here's my class at the moment:
public class AddressViewModel
{
public Guid Id { get; set; }
[Display(Name = "Address_Country", ResourceType = typeof(Resources.Shared))]
[Required]
public Guid CountryId { get; set; }
[Display(Name = "Address_AddressLine1", ResourceType = typeof(Resources.Shared))]
public string AddressLine1 { get; set; }
[Display(Name = "Address_AddressLine2", ResourceType = typeof(Resources.Shared))]
public string AddressLine2 { get; set; }
[Display(Name = "Address_AddressLine3", ResourceType = typeof(Resources.Shared))]
public string AddressLine3 { get; set; }
[Display(Name = "Address_AddressLine4", ResourceType = typeof(Resources.Shared))]
public string AddressLine4 { get; set; }
[Display(Name = "Address_AddressLine5", ResourceType = typeof(Resources.Shared))]
public string AddressLine5 { get; set; }
[Display(Name = "Address_PostalCode", ResourceType = typeof(Resources.Shared))]
public string PostalCode { get; set; }
}
Any help would be greatly received.
Thanks.