I have two models with a navigation property in one to the other. Model looks like this:
I am calling the two models in the same view. SuiteCategoryModels as the default and SuitesModels as a partial view.
public class SuiteCategoryModels
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int SuiteCatID { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Category")]
[StringLength(50, ErrorMessage = "The {0} must be at least 6 characters long.", MinimumLength = 6)]
public string CatName { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Category Description")]
[StringLength(500, ErrorMessage = "The {0} must be at least 6 characters long.", MinimumLength = 6)]
public string CatDesc { get; set; }
public virtual ICollection<SuitesModels> SuitesModels { get; set; }
}
and the second model like this:
public class SuitesModels
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int SuiteID { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Suite Name")]
[StringLength(50, ErrorMessage = "The {0} must be at least 6 characters long.", MinimumLength = 6)]
public string SuiteName { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Description")]
[StringLength(50, ErrorMessage = "The {0} must be at least 6 characters long.", MinimumLength = 6)]
public string SuiteDesc { get; set; }
[DataType(DataType.ImageUrl)]
[Display(Name = "Picture")]
public string SuitePix { get; set; }
[Required]
[Display(Name = "Rate")]
public int SuiteRate { get; set; }
[Required]
[Display(Name = "Persons Per Suite")]
public int PersonPerSuite { get; set; }
[Required]
[Display(Name = "Status")]
public bool SuiteStatus { get; set; }
public int SuiteCatID { get; set; }
public virtual SuiteCategoryModels SuiteCategory { get; set; }
}
I created a controller action to view like this:
public ActionResult Index()
{
var m = db.SuiteCategoryModels.ToList();
//ViewBag.BB =
//Dispose(false);
return View(m);
}
and the other like this:
public ActionResult SuitesIndex(int id = 0)
{
var mm = db.Suites.Select(r => r.SuiteCategory)
.Where(r => r.SuiteCatID == id);
//SuitesModels suitesmodels = db.Suites.Find(id);
if (mm == null)
{
return HttpNotFound();
}
return PartialView("SuitesIndex", mm.ToList());
}
But I have an error page stating: There is already an open DataReader associated with this Command which must be closed first..
What are the reasons of this error?
What do I do to correct this?
You need to add MultipleActiveResultSets=true; to your connection string.
Related
i have 3 models
public class UsersModel
{
[Key]
public int UserId { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Invalid Name Minimum Length is 5", MinimumLength = 5)]
public string Name { get; set; }
//20150090
public int? student_ID { get; set; }
[Display(Name = "transcript")]
public string transcript { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Invalid Name Minimum Length is 2", MinimumLength = 2)]
public string Department { get; set; }
[Required]
[Display(Name = "Phone")]
[DataType(DataType.PhoneNumber,ErrorMessage ="Invalid Phone Number")]
[Range(999999999, 9999999999)]
public int Phone { get; set; }
public int type { get; set; }
}
student
public class StudentsModel
{
[Key]
[Display(Name ="ID")]
public int StudentID { get; set; }
[Required]
public string Name { get; set; }
[Required]//20150090
public string student_ID { get; set; }
[Required]
[Display(Name = "Skills")]
public string Skills { get; set; }
[Required]
[Display(Name = "Gpa")]
[Range(1.00, 4.00, ErrorMessage = "It must be in range 0.00 to 4.00 :)")]
public float Gpa { get; set; }
[Required]
[Display(Name = "Leader")]
public string Leader { get; set; }
[Required]
[Display(Name = "transcript")]
public string transcript { get; set; }
[ForeignKey("UserId")]
public int UserId;
public UsersModel Users { get; set; }
[ForeignKey("IdeaId")]
public int? IdeaId;
public IdeaModel Idea { get; set; }
}
Idea
public class IdeaModel
{
[Required]
[Key]
public int IdeaId { get; set; }
[Required]
public string IdeaName { get; set; }
[Required]
public string IdeaDescription { get; set; }
[Required]
public string tools { get; set; }
public int? SetWith { get; set; }
[Required]
public int Prof1 { get; set; }
public int Prof2 { get; set; }
public int Prof3 { get; set; }
}
when i insert to the database user and student and idea
the foreign key in student model inserted with null value
this is the code for insertion
i want the foreign key in student model to inserted automatically
whit the values of primary key in usernodel and idea model how to make this?
public ActionResult RegisterLeader(regall reg)
{
if (ModelState.IsValid)
{
var user= db.Users.Add(reg.users);
var idea = db.Idea.Add(reg.idea);
var stu = db.Students.Add(reg.students[0]);
db.SaveChanges();
return View("RegisterLeaderPost");
//return Registerfinish();
}
}
this model have the three models
public class regall
{
public List<StudentsModel> students { get; set; }
public UsersModel users { get; set; }
public IdeaModel idea { get; set; }
}
You need to set the Idea property of the student so EF knows to make the relationship.
reg.students[0].Idea = reg.idea;
I am new to MVC 3 Data Annotations and I just want to ask that if its possible to add Validation on a Group of Fields in Model and Display the validation if none of it has Value?
this is the set of fields in my Data model
public class ContactModel
{
public Nullable<int> Id { get; set; }
[Display(Name = "Contact Firstname")]
[Required(ErrorMessage = "Required!")]
public string ContactFirstname { get; set; }
[Display(Name = "Contact Lastname")]
[Required(ErrorMessage = "Required!")]
public string ContactLastname { get; set; }
[Display(Name = "Contact Middlename")]
public string ContactMiddlename { get; set; }
[Display(Name = "Phone")]
[Required(ErrorMessage = "Required!")]
public string ContactPhone { get; set; }
[Display(Name = "Mobile ")]
[Required(ErrorMessage = "Required!")]
public string ContactMobile { get; set; }
[Display(Name = "Email")]
[Required(ErrorMessage = "Required!")]
public string ContactEmail { get; set; }
[Display(Name = "Job Title")]
[StringLength(50, ErrorMessage = "Max character reached!")]
public string ContactJobTitle { get; set; }
}
And I want to add validation if one from Phone,Mobile or Email doesn't have value
Thanks
You can implement IValidatableObject interface and add validation for all necessary properties:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if(string.IsNullOrEmpty(Phone) || string.IsNullOrEmpty(Mobile) || string.IsNullOrEmpty(Email))
{
yield return new ValidationResult("Some error message");
}
}
Of course you should remove [Required] attributes then from those properties.
The question I had was how are models supposed to be used? I don't think I am using them correctly. Whenever I make a change to the database (user table, in this case) and rebuild the model, my changes get erased and I end up making the changes again. The changes made are adding attributes and also another column(ConfirmPassword).
Edit: I am using EF 5
This is the model that was created by the database:
using System;
using System.Collections.Generic;
public partial class User
{
public User()
{
this.Documents = new HashSet<Document>();
}
public int UserId { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Grade { get; set; }
}
With my changes:
using System;
using System.Collections.Generic;
using CompareObsolete = System.Web.Mvc.CompareAttribute;
public partial class User
{
public User()
{
this.Documents = new HashSet<Document>();
}
[Key]
public int UserId { get; set; }
[Required]
[StringLength(15, MinimumLength = 3)]
[Display(Name = "Username*: ")]
public string Username { get; set; }
[Required]
[EmailAddress]
[StringLength(25)]
[Display(Name = "Email Address*: ")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(50, MinimumLength = 4)]
[Display(Name = "Password*: ")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm Password*: ")]
[CompareObsolete("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Your Grade*: ")]
public string Grade { get; set; }
}
1. Create UserMetaData Class
public class UserMetaData
{
[Key]
public int UserId { get; set; }
[Required]
[StringLength(15, MinimumLength = 3)]
[Display(Name = "Username*: ")]
public string Username { get; set; }
[Required]
[EmailAddress]
[StringLength(25)]
[Display(Name = "Email Address*: ")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(50, MinimumLength = 4)]
[Display(Name = "Password*: ")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm Password*: ")]
[CompareObsolete("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Your Grade*: ")]
public string Grade { get; set; }
}
2. Create new partial class in new .cs file and assign metadata class to there by using MetadataType attribute to it.
[MetadataType(typeof(UserMetaData))] // assign type of your metadata here.
public partial class User
{
}
I am quiet new with MVC. I am creating the user management module for authenticating and authorizing users withing that application. Hence, I created 2 models one for user roles and the other for user details.
I created two models like this:
public class RolesModels
{
public RolesModels()
{
this.Users = new HashSet<UserModels>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RoleId { get; set; }
[Required]
[DataType(DataType.Text)]
[StringLength(20, ErrorMessage = "The {0} must be at least 6 characters long.", MinimumLength = 6)]
[Display(Name = "Caption")]
public string Caption { get; set; }
[Display(Name = "Can Create")]
public bool createRole { get; set; }
[Display(Name = "Can View")]
public bool viewRole { get; set; }
[Display(Name = "Can Modify")]
public bool modifyRole { get; set; }
[Display(Name = "Can Delete")]
public bool deleteRole { get; set; }
public virtual ICollection<UserModels> Users { get; set; }
}
public class UserModels
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int user_id { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "User Name")]
[StringLength(20, ErrorMessage = "The {0} must be at least 3 characters long.", MinimumLength = 3)]
public string user_name { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
[StringLength(10, ErrorMessage = "The {0} must be at least 4 characters long.", MinimumLength = 4)]
public string user_pass { get; set; }
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
[StringLength(50, ErrorMessage = "The {0} must be at least 6 characters long.", MinimumLength = 6)]
public string UserEmail { get; set; }
[Display(Name = "Registeration Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime RegDate { get; set; }
[Display(Name = "Enable")]
public bool status { get; set; }
[Required]
public int RoleId { get; set; }
[Display(Name = "Roles")]
public virtual RolesModels Roles { get; set; }
}
and I have the registration controller action like this:
[HttpGet]
public ActionResult registration()
{
// var md = from m in db.RolesModels
// orderby m.Caption descending
// select m;
// Html.DropDownList("Roles", new SelectList(ViewBag.Roles), new { #id = "dropdown" });
ViewBag.Roles = db.RolesModels.Select(r => r.Caption);
ViewBag.RolesId = db.RolesModels.Select(r => r.RoleId);
return View();
}
I created a view for the registration with a dropdownlist like this:
#Html.DropDownList("RoleId", new SelectList(ViewBag.Roles), new { #id = "dropdown" })
My HTTPPost is here
[HttpPost]
public ActionResult registration(Solnet_HotelSuite.Models.UserModels user)
{
if (ModelState.IsValid)
{
using (var db = new DBEntity())
{
var sysUser = db.UserModels.Create();
sysUser.user_name = user.user_name;
sysUser.user_pass = user.user_pass;
sysUser.UserEmail = user.UserEmail;
sysUser.RegDate = user.RegDate;
sysUser.RoleId = user.RoleId;
//sysUser.Roles = user.Roles;
sysUser.status = user.status;
db.UserModels.Add(sysUser);
db.SaveChanges();
}
}
return View(user);
}
But whenever I clicked on Register user, I get the error :
Value cannot be null. Parameter name: items
What am I doing wrong?
The items you put in the viewbag are missing after the postback. Try changing the end of your HttpPost code to:
ViewBag.Roles = db.RolesModels.Select(r => r.Caption);
ViewBag.RolesId = db.RolesModels.Select(r => r.RoleId);
return View(user);
You may need to adjust this code as the db object may be out of scope at this point.
I had been struggling with this issue since morning. I have the following class in my domain service.
[MetadataTypeAttribute(typeof(CompanyRecord.CompanyRecordMetadata))]
public partial class CompanyRecord
{
// This class allows you to attach custom attributes to properties
// of the CompanyRecord class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class CompanyRecordMetadata
{
// Metadata classes are not meant to be instantiated.
private CompanyRecordMetadata()
{
}
public Nullable<char> AccessToClearance { get; set; }
public Nullable<char> AccessToMarketplace { get; set; }
public Nullable<bool> Active { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public Nullable<int> AllotedHDSpace { get; set; }
public string City { get; set; }
public int CompanyID { get; set; }
public Binary CompanyLogo { get; set; }
[Required(ErrorMessage = "Company Name is required and must be unique.")]
public string CompanyName { get; set; }
[Range(1, Int32.MaxValue, ErrorMessage = "Company Type is required.")]
public int CompanyTypeID { get; set; }
[Range(1, Int32.MaxValue, ErrorMessage = "Country is required.")]
public Nullable<int> CountryID { get; set; }
public string Description { get; set; }
//[RegularExpression(pattern: #"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|tv|COM|ORG|NET|GOV|MIL|BIZ|INFO|MOBI|NAME|AERO|JOBS|MUSEUM|TV|Com|Org|Net|Gov|Mil|Biz|Info|Mobi|Name|Aero|Jobs|Museum|Tv)\b", ErrorMessage = "Please provide a valid email address")]
[RegularExpression(pattern: #"(\w[-._\w]*\w#\w[-._\w]*\w\.[a-zA-z]{2,6})", ErrorMessage = "Please provide a valid email address")]
public string EmployeeEmail { get; set; }
//[RegularExpression(pattern: #"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|tv|COM|ORG|NET|GOV|MIL|BIZ|INFO|MOBI|NAME|AERO|JOBS|MUSEUM|TV|Com|Org|Net|Gov|Mil|Biz|Info|Mobi|Name|Aero|Jobs|Museum|Tv)\b", ErrorMessage = "Please provide a valid email address")]
//(\w[-._\w]*\w#\w[-._\w]*\w\.\w{2,3})
[RegularExpression(pattern: #"(\w[-._\w]*\w#\w[-._\w]*\w\.[a-zA-z]{2,6})", ErrorMessage = "Please provide a valid email address")]
[Required(ErrorMessage = "Email is required.")]
public string Email { get; set; }
[StringLength(10, ErrorMessage = "Phone Ext. should not be more than 10 chars.")]
public string EmployeePhoneExt { get; set; }
[StringLength(20, ErrorMessage = "Phone No. should not be more than 20 chars.")]
[RegularExpression(pattern: #"^[0-9\-\(\) ]*[0-9\-\(\)]*$", ErrorMessage = "Please provide a valid Phone No.")]
public string EmployeePhoneNo { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Range(0, int.MaxValue, ErrorMessage = "Number of projects should be lower than 2,147,483,647.")]
public Nullable<int> NoOfProjects { get; set; }
public Nullable<int> NoOfUsers { get; set; }
[StringLength(10, ErrorMessage = "Phone Ext. should not be more than 10 chars.")]
public string PhoneExt { get; set; }
[StringLength(20, ErrorMessage = "Phone No. should not be more than 20 chars.")]
[Required(ErrorMessage = "Phone No. is required.")]
[RegularExpression(pattern: #"^[0-9\-\(\) ]*[0-9\-\(\)]*$", ErrorMessage = "Please provide a valid Phone No.")]
public string PhoneNo { get; set; }
[RegularExpression(pattern: #"^[a-zA-Z0-9\-\(\)\* ]*[a-zA-Z0-9\-\(\)\*]*$", ErrorMessage = "Postal codes cant' contain special characters except for -, (, ), * and spaces.")]
public string PostalCode { get; set; }
public string Province { get; set; }
public string Website { get; set; }
public int MarketID { get; set; }
public int AffiliationID { get; set; }
public string CallLetter { get; set; }
}
}
PROBLEM: I need to create a validation rule that woudl require MarketID and Affiliation ID only when CompanyTypeID is equivalent to 1, 3, 5, 9 and 11 is there someone out there who has an idea on how to solve this?
You should use the custom validation.
There are some topics for your question below:
1 http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(vs.95).aspx
2 http://blogs.microsoft.co.il/blogs/bursteg/archive/2009/04/14/net-ria-services-custom-validation.aspx