about using "virtual ICollection..." in my model design? - asp.net

I my asp.net mvc HR web apps, in my entity data model, in one page razor view, I have more than one model of data loaded and displayed, for example, in The Employee razor view, I want to display Employee data information on the top, but as the same I also want to display other ralated data with this employee such as Salary, Performance and Reveiw, all of these related data are seperated SQL table which is different EF model.
So to make it simple, one employee profile model has its ralated Salary, Performance and Review model (SQL table), so I use "virtual ICollection" in Employee Profile model.
In Employee Profile model: I have these codes:
public class EmpProfile
{
public int ID { get; set; }
[Display(Name = "Employee Name")]
public string EmpName { get; set; }
[Display(Name = "Employee Number")]
public string EmpNum { get; set; }
[Display(Name = "Employee Title")]
public string EmpTitle { get; set; }
[Display(Name = "Department")]
public virtual ICollection<PerfPlan> PerfPlans { get; set; }
public virtual ICollection<ProgReview> ProgReviews { get; set; }
public virtual ICollection<ProgEvaluation> ProgEvaluations { get; set; }
public virtual ICollection<DevelopPlan> DevelopPlans { get; set; }
}
And in Employee Performance model, I have these codes (Salary and Review model are similar as this one):
public class Performance
{
public int ID { get; set; }
public int EmpProfileID { get; set; }
[Required(ErrorMessage = "{0} is required.")]
[Display(Name = "Name*:")]
public string EmpName { get; set; }
[Required(ErrorMessage = "Please enter your Employee Number.")]
[Display(Name = "Employee No.*:")]
public string EmpNum { get; set; }
......
public virtual EmpProfile EmpProfile { get; set; }
}
Now, after I build them, in my performance contoller, I found this line code in Create method:
ViewBag.EmpProfileID = new SelectList(db.EmpProfiles, "ID", "EmpName");
and in Create view generated by the controller, the EmpProfileID dropdownlist field is generated
#Html.DropDownList("EmpProfileID", String.Empty)
Can anybody tell me why the code ViewBag.EmpProfileID = new SelectList(db.EmpProfiles, "ID", "EmpName"); is generated in Create methed?

Because all the generator knows or cares about is that EmpProfileID is a non-nullable int, so it creates a field to edit it. Since it's the id for a foreign key, it helpfully gives you a list of EmpProfile ids to choose from. If you don't want this field directly editable, you can remove it or change it to a hidden field. You just need to keep in mind that it will need to be set somehow, some way before you check ModelState.IsValid or you'll fail validation.

Related

How to dynamically add rows to my table and postback the data to view

As the question suggests I am using ENTITY FRAMEWORK in my ASP.NET application in which I have a table which the user can add rows to and input data into it. I need to know how I can post this data back to controller.
My models : (There were generated by EF when i used database first approach)
public partial class TRA_FORMS
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public TRA_FORMS()
{
this.TRA_ITEMS = new HashSet<TRA_ITEMS>();
}
public int ID { get; set; }
[Display(Name = "Name of TRA")]
public string NAME_OF_TRA { get; set; }
[Display(Name = "Requested amount")]
public Nullable<double> AMOUNT_REQUESTED { get; set; }
[Display(Name = "Name of commitee member making application")]
public string COMMITEE_MEMBER_NAME { get; set; }
[Display(Name = "Date of last AGM")]
public Nullable<System.DateTime> DATE_OF_AGM { get; set; }
[Display(Name = "Signed")]
public string SIGNED { get; set; }
[Display(Name = "Dated")]
public Nullable<System.DateTime> DATED { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<TRA_ITEMS> TRA_ITEMS { get; set; }
}
public partial class TRA_ITEMS
{
public int ITEM_ID { get; set; }
[Display(Name = "Description of Items")]
public string DESC_OF_ITEMS { get; set; }
[Display(Name = "Quantity")]
public Nullable<int> QUANTITY { get; set; }
[Display(Name = "Cost")]
public Nullable<double> COST { get; set; }
[Display(Name = "From ID")]
public Nullable<int> FORM_ID { get; set; }
public virtual TRA_FORMS TRA_FORMS { get; set; }
}
My controller:
[HttpPost]
public ActionResult Index(TRA_FORMS traForms)
{
return View();
}
I'm not showing my view here as It's wrong and I dont know how to go about it. But the view accepts a model of type TRA_FORMS. I have a table in this view (regular html ) which has 3 columns - each for properties from the TRA_ITEMS model. The Desc of items, quantity and cost. Users can add any number of items to this table. Ideally on postback it should postback a List which holds each item added by the user but i don't know how to do this. I've looked at several Stack overflow questions related to this and been looking for solutions the whole day but I'm a newbie to ASP.NET so having trouble applying most answers i found to my scenario.

How to handle validation for Relationship PK and FK in MVC5

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()

ASP.NET MVC 5 get 3 models data in 1 view

I am trying to do small application in mvc 5. In this I have 3 models say Organisation model, Product model and Package model.
Organisation model:
namespace Own.Models
{
public class OrganisationViewModel
{
[Key]
public int OrganisationID { get; set; }
[Required(ErrorMessage = "Please enter Organisation name")]
public string OrganisationName { get; set; }
[Required(ErrorMessage = "Please enter organisation address")]
public string OrganisationAddress { get; set; }
Package Model:
namespace Own.Models
{
public class PackageViewModel
{
[Key]
public int PackageID { get; set; }
[Required(ErrorMessage = "Please enter packagename")]
public string Packagename { get; set; }
[Required(ErrorMessage = "Please enter packagedescription")]
public string PackageDescription { get; set; }
Product Model:
namespace Own.Models
{
public class ProductViewModel
{
[Key]
public int ProductID { get; set; }
[Required(ErrorMessage = "Please enter Product Name")]
public string ProductName { get; set; }
[Required(ErrorMessage = "Please enter Product Description")]
public string ProductDescription { get; set; }
Now, I need to create another model named Submission model. Here in this Submission view I want the three dropdown lists for Organisation, Product and Package. If I select Organisation dropdown by selecting item in that dropdown it should display Organisation ID, Organisation Name and Organisation Address (just it should display details, read only).
Similarly for Package and Product also it should display all details and after displaying full details in one view at bottom there should be button to save the details. Here I am not using any database. Only some static data. How to display all 3 models data in that final model view? and how to get that read only data when selecting the drop down.
You can create anonamous type to concat fields
obj =db.Org
.Where(...)
.ToList()
.Select(s => new
{ ID=s.ID,
Description = string.Format("{0}-- £{1}", s.Name,s.Description)
});
Viewbag.OrgDdl=new SelectList(obj,"ID","Description");
In you view, you can use it like this
#Html.DropDownListFor(m1 => m1.ID, ViewBag.OrgDdl as IEnumerable<SelectListItem>)
Hope this helps
The best approach to this issue is creating a View Model consisting three mentioned objects as properties. Something like:
public class MyNewViewModel
{
public OrganisationViewModel MyOrganisation { get; set; }
public PackageViewModel MyPackage { get; set; }
public ProductViewModel MyProduct { get; set; }
}
Then you could populate your properties inside MyNewViewModel constructor at first or you can populte them seperatly during any action or ajax callback. So you will have your whole related data on view.

Upload Images in asp.net mvc 3 aspx syntax for custom class without database

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
}

How to set a Foreign Key relationship manually in LINQ To SQL

I've been working through the book Pro ASP.NET MVC 2 Framework by Steven Sanderson. So far it's been phenominal... just when i think I know a decent amount I find a book that shows me just how little I know.
One of the things I know little about is how to use LINQtoSQL. In Steven's book, chapters 4-6 create a very nice little shopping cart. I went through the tutorial and got everything working. Now I want to modify the cart to use a Category table instead of storing the category name as a varchar in the Product table.
Here's the Product table object with my changes to have CategoryID as a foreign key relationship to the Categories Table.
[Table(Name="Products")]
public class Product
{
[HiddenInput(DisplayValue=false)]
[Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
public int ProductID { get; set; }
[Required(ErrorMessage="Please enter a product name")]
[Column] public string Name { get; set; }
[Required(ErrorMessage="Please enter a description")]
[DataType(DataType.MultilineText)]
[Column] public string Description { get; set; }
[Required]
[Range(0.01, double.MaxValue, ErrorMessage="Please enter a positive price")]
[Column] public decimal Price { get; set; }
[Required(ErrorMessage="Please enter a category")]
[Column] public int CategoryID { get; set; }
internal EntityRef<Category> _category;
[System.Data.Linq.Mapping.Association(ThisKey = "CategoryID", Storage = "_category")]
public Category Category {
get { return _category.Entity; }
internal set { _category.Entity = value; CategoryID = value.CategoryID; }
}
[Column] public byte[] ImageData { get; set; }
[ScaffoldColumn(false)]
[Column] public string ImageMimeType { get; set; }
And here is my Category class
[Table(Name="Categories")]
class Category
{
[Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
internal int CategoryID { get; set; }
[Column]
public int ParentCategoryID { get; set; }
[Column]
[Required]
public string Name { get; set; }
}
When I tried to build this code, i got an error that I don't understand:
Inconsistent accessibility: property type 'SportsStore.Domain.Entities.Category'
is less accessible than property 'SportsStore.Domain.Entities.Product.Category'
What does that mean / How would I fix this?
Your class "Categroy" is less visibly then "Product". "Product" has a public Property "Category" which is public. This is the "Inconsistent accessibility".
You have to declare your class "Category" public like "Product"

Resources