I am a complete newbie in asp.net mvc. And i'm stuck with some problem and don't yet know how to solve it. I googled, found some useful things, but they haven't helped me with solving my problem. So let's begin with what i have now:
public partial class Dish
{
public Dish()
{
PortionFood = new HashSet<PortionFood>();
}
[Key]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[JsonIgnore]
public virtual DishCategory DishCategory { get; set; }
[JsonIgnore]
public virtual ICollection<PortionFood> PortionFood { get; set; }
}
}
// Food class in a separate file
public partial class Food
{
public Food()
{
PortionFood = new HashSet<PortionFood>();
}
[Key]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public float Proteins { get; set; }
public float Fat { get; set; }
public float Carbs { get; set; }
public float Ccal { get; set; }
public float? Sugar { get; set; }
public float? AmountOfWater { get; set; }
[ForeignKey("FoodCategory")]
public int IdFoodCategory { get; set; }
[ForeignKey("FoodConsistencyType")]
public int IdFoodConsistencyType { get; set; }
[JsonIgnore]
public virtual FoodCategory FoodCategory { get; set; }
[JsonIgnore]
public virtual ICollection<PortionFood> PortionFood { get; set; }
}
}
// Portion Food Class in a separate file
public partial class PortionFood
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[ForeignKey("Food")]
public int IdFood { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[ForeignKey("Dish")]
public int IdDish { get; set; }
public float Amount { get; set; }
public bool IsDeleted { get; set; }
public virtual Dish Dish { get; set; }
public virtual Food Food { get; set; }
}
}
PortionFood just specifies what amount of what Food is inside which Dish.
Now i have views for classes Dish and Food, and i am able to add new object of each of these two classes(by filling in the view fields and pressing the button) to DB, i am able to edit an existing Dish && an existing Food. See list of all existing Food && Dish objects.
What i want:
When adding/editing a Dish there must be a possibility to add a PortionFood object releated to current Dish(which we are editing or adding). Just by selecting a FoodId in a dropdown list, setting an amount and clicking the button. The PortionFood object must be inserted to PotionFood collection of related Dish and related Food
How can i implement it?
If there're any uncretainties write in a comment, and i'll try to make it clear.
Thank's for help!
I think I see your problem now, you need to populate from ICollection not to it. In that case I suggest using List<SelectListItem> because you can then use DropDownListFor html helper.
For example:
public class ViewModel {
private readonly List<PortionFood> _foods;
[Display(Name = "Pick a portion")]
public int SelectedFoodItem { get; set; }
public IEnumerable<SelectListItem> FoodPortionItems
{
get { return new SelectList(_foods, "Id", "Name"); }
}
}
public class PortionFood {
public int Id { get; set; }
public string Name { get; set; }
}
//In your Razor View:
#Html.LabelFor(m => m.SelectedFoodItem)
#Html.DropDownListFor(m => m.SelectedFoodItem, Model.FoodPortionItems)
That should help you populate the dropdown.
PS: I usually like to use ViewModels instead of Models here, that way you only have what you need in the View
Related
I Have This Product Class In My Project
public string Title { get; set; }
public int CategoryId { get; set; }
public int ProductDetailId { get; set; }
public int BrandId { get; set; }
public Gender GenderTypeId { get; set; }
public int ProductCount { get; set; }
public decimal? Price { get; set; }
public double? Discount { get; set; }
public string Description { get; set; }
public DateTime CreateDate { get; set; }
public DateTime? EditDate { get; set; }
public virtual ProductDetail ProductDetail { get; set; }
I Want A ProductDetails Class For Different Products
For Example:
When Customer Select TV Product ProductDetails Shows Width&Height&Inch Or When Selected A T-Shirt It Shows S-L-XL-XXL And So On...
Thanks
You can use inheritance with EF core
First we define the C# class inheritance:
public class Product
{
public string Title { get; set; }
//define the rest of the properties
public int ProductDetailId { get; set; }
public ProductDetails ProductDetails { get; set; }
}
public abstract class ProductDetails
{
public string ProductDetailType { get; set; }
public int Id { get; set; }
}
public class TvDetails : ProductDetails
{
public float Width { get; set; }
public float Height { get; set; }
}
public class ClothDetails : ProductDetails
{
public string Size { get; set; }
}
Now we need to define how to map it with EF core. there are multiple approaches as it says in the documentation I mentioned above.
By default EF core will use Table-per-hierarchy and discriminator.
you can also define the discriminator:
modelBuilder.Entity<ProductDetails>()
.HasDiscriminator(p => p.ProductDetailType );
Now the last problem would be we querying, we can simply cast the object based on the discriminator value.
I have the following models
Patient Class:
public class Patient
{
public int PatientID { get; set; }
public virtual Salutation salutation { get; set; }
public int SalutationID { get; set; }
public string Surname { get; set; }
public string Firstname { get; set; }
[Display(Name = "Date of Birth")]
[DisplayFormat(DataFormatString="{0:d}", ApplyFormatInEditMode=true)]
public DateTime DOB { get; set; }
public string RegNo { get; set; }
public DateTime RegDate { get; set; }
public string Occupation { get; set; }
}
VatalSigns Class
public class VitalSign
{
public int VitalSignID { get; set; }
public string Sign { get; set; }
[Display(Name = "Lower Limit")]
public int? LowerHold { get; set; }
[Display(Name = "Upper Limit")]
public int? UpperHold { get; set; }
[Display(Name = "Unit Of Measurment")]
public string Units { get; set; }
}
PV class that stores VitalSigns for each patient
public class PVSign
{
public long PVSignId { get; set; }
[Display(Name = "Patient")]
public int PatientID { get; set; }
public VitalSign VitalSigns { get; set; }
//public IList<VitalSign> VitalSigns { get; set; }
public Patient patient { get; set; }
}
Now the problem I have is that I have not been able to get display on one from to enter the details. I want to select the Patient and the different Vitals signs will appear and I will save the ones I need to the PVSign table.
I have tired all sorts of samples from the web. You can see from the code below, this is the index stub:
public ActionResult Index()
{
var pVSigns = db.PVSigns.Include(p => p.patient).Include(p => p.PVSignId).Include(p => p.VitalSigns);
//var pVSigns = from o in db.Patients join o2 in db.PVSigns
//List<object> myModel = new List<object>();
//myModel.Add(db.Patients.ToList());
//myModel.Add(db.VitalSigns.ToList());
//return View(myModel);
return View(pVSigns.ToList());
}
How to I solve this issue. I am new to MVC, if it was Webforms, I would have been through with this project.
Thank you.
There is no single answer(solution) to this(your) problem. It depends on how you want to design/build/achieve your solution.
The simple, brute solution : Just have a view model as a wraper that has as his properties the classes(models) you made and work around that,
public class FullPatientDetailsViewModel
{
public Patient { get; set;}
public List<PVSign> PatientPvSigns { get; set;} // Patien PV Signs
}
Or use just a PatientViewModel and load his PVSigns async with Ajax.
There is no simple best solution, it all depends about what do you want to achieve as a bigger picture.
I've answered a similar question here. As Alexandru mentioned, the easiest and most straightforward way would be to wrap your models inside a ViewModel. You can read about other ways to implement this here.
I am trying to Deserialise a JSON object in to a strongly typed .net object/Type. This is the object I want to create from the JSON
[Serializable]
public class CartItem
{
[Key]
public int Id { get; set; }
public virtual Product Product { get; set; }
public virtual List<SelectedProductOption> SelectedProductOptions { get; set; }
public virtual Cart Cart { get; set; }
public int Quantity { get; set; }
}
So you have the whole picture, I am also going to post the definition for the other objects that make up CartItem, but remember Its CartItem I want to ultimately end up with
[Serializable]
public class Product
{
[Key]
public int Id { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public virtual Category Category { get; set; }
}
[Serializable]
public class Category
{
[Key]
public int Id { get; set; }
public string CategoryName { get; set; }
public string ImageURL { get; set; }
}
In my CartItem Object I have a collection of SelectedProductOption (THIS IS WHERE I AM HAVING PROBLEMS) This is the definition for a SelectedProductOption
[Serializable]
public class SelectedProductOption
{
public Option Option { get; set; }
public AllowedOptionValue Value { get; set; }
}
[Serializable]
public class Option
{
[Key]
public int Id { get; set; }
public string OptionName { get; set; }
public virtual OptionGroup OptionGroup { get; set; }
}
[Serializable]
public class AllowedOptionValue
{
[Key]
public int Id { get; set; }
public virtual Option Option { get; set; }
public string OptionValue { get; set; }
public string OptionCaption { get; set; }
public decimal? PriceOffSet { get; set; }
public bool? IsPercentageOffSet { get; set; }
}
Now this is the JSON Object that I am trying to serialize
{\"Product\":{\"Id\":1,\"Price\":3.5,\"ProductName\":\"Rice Meal One\",\"Category\": {\"Id\":1,\"CategoryName\":\" Rice Meals\",\"ImageURL\":\" \"},\"SelectedProductOptions\":[{\"Option\":{\"Id\":1,\"OptionName\":\"OptionName1\",\"OptionGroup\":{\"Id\":1,\"OptionGroupName\":\"Option Group\"}},\"Value\":{\"Id\":1,\"Option\":{\"Id\":4,\"OptionName\":\"OptionName2\",\"OptionGroup\":{\"Id\":1,\"OptionGroupName\":\"Option Group2\"}},\"OptionValue\":\"12123123\",\"OptionCaption\":\"12123123\",\"PriceOffSet\":3.2,\"IsPercentageOffSet\":true}},{\"Option\":{\"Id\":1,\"OptionName\":\"dsa\",\"OptionGroup\":{\"Id\":1,\"OptionGroupName\":\"asdas\"}},\"Value\":{\"Id\":1,\"Option\":{\"Id\":1,\"OptionName\":\"dsa\",\"OptionGroup\":{\"Id\":1,\"OptionGroupName\":\"asdas\"}},\"OptionValue\":\"12123123\",\"OptionCaption\":\"12123123\",\"PriceOffSet\":3.2,\"IsPercentageOffSet\":true}}]}}
So when I call:
CartItem cartItem = js.Deserialize<CartItem>(formData);
CartItem.Product has the right values
CartItem.Product.Category has the Right Values
but
CarItem.SelectedProductOptions is null...
Where am I going wrong? the only property that is not working, any ideas on how to fix it?
There is no need to do it manually, asp.net MVC will do it for you :)
In view create a form, which contains all needed fields:
#model CartItem;
<form action="/mycontroller/myaction">
#Html.TextBoxFor(m => mode.ProductName)
...
<button type=submit>OK</button>
</form>
and define your controllers action like:
[HttpPost]
public ActionResult myaction(CartItem carItem)
{
...
}
the carItem object should contain all the data that you entered in the view
You can see my previous question which related with many to many relation but with auto generated mapping table.
I have 2 model, HrTraining and HrPerson. Any people can be assigned to one or more Trainings. You can see my model as below
public class HrTraining
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<HrMapTrainingPerson> HrMapTrainingPerson { get; set; }
}
public class HrMapTrainingPerson
{
public int Id { get; set; }
public string Status { get; set; }
public int HrTrainingId { get; set; }
public int HrPersonId { get; set; }
public virtual HrTraining HrTraining { get; set; }
public virtual HrPerson HrPerson { get; set; }
}
public class HrPerson
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<HrMapTrainingPerson> HrMapTrainingPerson { get; set; }
}
How can i take all training objects which assingned to a person with efficient way.
So you want to find a person, and get all the trainings assigned to it? There are lot of ways.. but using your models, this could be something like this
var trPersons = dbContext.HrPerson.Find(idPerson).HrMapTrainingPerson.ToList();
foreach(var trPerson in trPersons) {
var training = trPerson.HrTraining;
//do what you want, here you can get trPerson.HrTraining.Name for instance
}
Ok dead basic question, I'm a self taught developer so often I seem to have gaps where I can't decide which was is the right way... and this is one of them!! Simple I have a view model which has a collection of child items. But where these classes are defined I can't decide if the child object should be a subclass of the parent...
For example this:
public class ActionChartViewModel
{
public IEnumerable<ActionChartItemViewModel> Items { get; set; }
public TextPagingInfo TextPagingInfo { get; set; }
}
public class ActionChartItemViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Rating { get; set; }
public string Comment { get; set; }
public string AssignedToUserName { get; set; }
public string ContactRequested { get; set; }
public bool Resolved { get; set; }
public int NoteCount { get; set; }
public string ContactDetails { get; set; }
public int ResponseId { get; set; }
}
Or this:
public class ActionChartViewModel
{
public IEnumerable<Item> Items { get; set; }
public TextPagingInfo TextPagingInfo { get; set; }
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Rating { get; set; }
public string Comment { get; set; }
public string AssignedToUserName { get; set; }
public string ContactRequested { get; set; }
public bool Resolved { get; set; }
public int NoteCount { get; set; }
public string ContactDetails { get; set; }
public int ResponseId { get; set; }
}
}
I prefer the second one for a code readability and simplicity front, but I don't know the pros and cons of subclasses. What would you guys think??
Thanks in advance!!
I would use separate classes (in same file) as opposed to an inner class. Inner class would be useful when it serves only the parent class, i.e. would not be accessed from outside of the parent class, only by the parent class methods, etc. In your case the inner class needs to be used on view(s), so I don't see a need for it. The first option, i.e. separate classes, is actually simpler to me and reads better.
"SubClass" is when you create more concrete implementations (inherits) of its types. As # bloparod says, you're doing "inner classes". I also rarely use inner classes. Sometimes I use some private or internal classe as a temporary. If you do that, you will need to create with the sintaxe like:
ActionChartViewModel.Item item = new ActionChartViewModel.Item();
I usually separete files and use public classes but sometimes when I have lots and lots of ViewModel, I think a good pratice is to keep all of the same category of ViewModels on a single file and inherited when necessary, for sample:
File: ProductViewModel.cs
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string CategoryName { get; set; }
}
public class ProductDetailViewModel : ProductViewModel
{
public int Stocke { get; set; }
public string Obs { get; set; }
public IEnumerable<ProductMovViewModel> Inventory
/* other properties */
}
public class ProductMovViewModel
{
public int Id { get; set; }
public DateTime Date { get; set;
public int Amout { get; set; }
}
As a good pratice too you can separete in files your ViewModels, as you prefer.