asp.net mvc 3 razor Two controllers in one view - c#

Want to use two models in one view. I have two controllers one for current user
public class ProfileModel
{
public int ID { get; set; }
public decimal Balance { get; set; }
public decimal RankNumber { get; set; }
public decimal RankID { get; set; }
public string PorfileImgUrl { get; set; }
public string Username { get; set; }
}
and second for firends
public class FriendsModel
{
public int ID { get; set; }
public string Name { get; set; }
public string ProfilePictureUrl { get; set; }
public string RankName { get; set; }
public decimal RankNumber { get; set; }
}
Profile model contains always one item and Friend model contains list
I have made new model which contains both models :
public class FullProfileModel
{
public ProfileModel ProfileModel { get; set; }
public FriendsModel FriendModel { get; set; }
}
I tried to fill FullProfile model like this
List<FriendsModel> fmList = GetFriendsData(_UserID);
FullProfileModel fullModel = new FullProfileModel();
fullModel.ProfileModel = pm;
fullModel.FriendModel = fmList.ToList();
but visual studio gives an error on .ToList()
error:
Cannot implicitly convert type 'System.Collections.Generic.List<NGGmvc.Models.FriendsModel>' to 'NGGmvc.Models.FriendsModel'
Please advice me something how i can show two models in single view.
p.s. im using mvc3 razor view engine
Thanks

You are trying to set a property of type FriendsModel with a value of List.
public FriendsModel FriendModel { get; set; }
Change to:
public class FullProfileModel
{
public ProfileModel ProfileModel { get; set; }
public IList<FriendsModel> FriendModel { get; set; }
}

Correct your ViewModel
public class FullProfileModel
{
public ProfileModel ProfileModel { get; set; }
public IList<FriendsModel> FriendModels { get; set; }
}

I think you need collection
public class FullProfileModel
{
public ProfileModel ProfileModel { get; set; }
public List<FriendsModel> FriendModels { get; set; }
}

Related

Is it possible to add array of data in child entity?

I have issue that I hope someone here will be able to help me.For this exercise I`m using aspnetboilerplate framework.
So I create 3 entity and they ALL work good (at least I guess they work good)
Little bit recap of project
One Recepie HAVE one or more Ingredient
Ingrident.cs
public class Ingrident : Entity
{
public string Name { get; set; }
public Master Master { get; set; }
public int? MasterId { get; set; }
public Recepie Recepie { get; set; }
public int? RecepieId { get; set; }
}
Master.cs
public class Master : Entity
{
public string Name { get; set; }
public string? Image { get; set; }
public string? ShortDescription { get; set; }
public string? FullDescription { get; set; }
public string? Keywords { get; set; }
public string Slug { get; set; }
public int? Count { get; set; }
public List<Ingrident> Ingridents { get; set; }
}
Recepie.cs
public class Recepie : Entity
{
public string RecepieName { get; set; }
public Ingrident Ingridents { get; set; }
}
With this database structure I can add Recepie and add only one ingredient when I try to send [] of Ingredient its show me DTO error.
And here is RecepieAppService.cs
public class RecepieAppService : AsyncCrudAppService<IndexIngrident.Entities.Recepie,RecepieDto>
{
private readonly IRepository<IndexIngrident.Entities.Recepie> _repository;
private readonly IRepository<IndexIngrident.Entities.Ingrident> _ingRepository;
public RecepieAppService(IRepository<IndexIngrident.Entities.Recepie> repository, IRepository<IndexIngrident.Entities.Ingrident> ingRepository)
: base(repository)
{
_repository = repository;
_ingRepository = ingRepository;
}
public List<RecepieFullGetDto> GetAllIncluded()
{
var result = _repository.GetAllIncluding(x => x.Ingridents , x => x.Ingridents.Master);
Debug.WriteLine(result);
return ObjectMapper.Map<List<RecepieFullGetDto>>(result);
}
}
RecepieDto.cs
[AutoMap(typeof(IndexIngrident.Entities.Recepie))]
public class RecepieDto : EntityDto
{
public string RecepieName { get; set; }
public IngridentRecepieDto Ingridents { get; set; }
}
public class IngridentRecepieDto : EntityDto
{
public string Name { get; set; }
public int RecepieId { get; set; }
}
Using AsyncCrudAppService my CRUD is automatically generated and I`m able to create new Recepie but when I try to do something like this
I get error
you need to add the mapping of objects in both directions, [AutoMapTo (typeof (RecepieDto))] and [AutoMapFrom (typeof (Recepie))], and verify that you have the class, inherits AutomapperProfile

Whats is a viable approach for a Template Data Model consists of two lists?

At the moment im working on a project where you can create a template for a report. At this point im struggling between two viable approaches for the entity model and I'm not sure which way is from the architectural approach the way to go.
A template consists of the following attributes:
Id
Name
List of Materials
List of Services
For each material and service position I have to declare a count of how many is needed.
I have two approaches how I can build it:
Approach I:
public class Template
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<TemplatePosition> Positions { get; set; }
}
public class TemplatePosition
{
public int Id { get; set; }
public int Count { get; set; }
public Service Service { get; set; }
public Material Material { get; set; }
public Template Template { get; set; }
[NotMapped]
public TemplatePositionTyp Type => this.Material != null ? TemplatePositionTyp.Material : TemplatePositionTyp.Service;
}
public enum TemplatePositionTyp
{
Material = 1,
Service = 2
}
Approach II:
public class Template
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<TemplateMaterialPosition> MaterialPositions { get; set; }
public ICollection<TemplateServicePosition> ServicePositions { get; set; }
}
public class TemplateMaterialPosition
{
public int Id { get; set; }
public int Count { get; set; }
public Material Material { get; set; }
public Template Template { get; set; }
}
public class TemplateServicePosition
{
public int Id { get; set; }
public int Count { get; set; }
public Service Service { get; set; }
public Template Template { get; set; }
}
I wish someone can explain me which one is the one to go and even the downside of the other approach.

ASP.NET MVC 5, how to enable validation annotation on viewmodel that composes other view models?

Well I have a very complex User Profile system in a social network application I am building. The profile page has tabs that distinguishes each category of user profile information: Basic, Education, Job. There is a UserProfileViewModel sitting on top of everything, which composes of inner view models such as BasicViewModel, EducationViewModel and JobViewModel. Consider the structure as below:
public class ProfileViewModel
{
public string id { get; set; }
public BasicViewModel basic { get; set; }
public EducationViewModel education { get; set; }
public JobViewModel job { get; set; }
}
public class BasicViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? DateOfRegistration { get; set; }
public DateTime? DateOfBirth { get; set; }
public string Gender { get; set; }
public string PhoneNumber { get; set; }
[Display(Name = "Biography")]
public string Biography { get; set; }
public string NickName { get; set; }
public string FavoriteQuotes { get; set; }
}
public class EducationViewModel{
public string EducationStatus { get; set; }
public List<University> Universities { get; set; }
public string CourseStatus { get; set; }
public string CourseSpecialization { get; set; }
public List<string> EducationEvents { get; set; }
}
public class JobViewModel
{
public string WorkStatus { get; set; }
public List<Company> Companies { get; set; }
}
public abstract class Organization
{
public string Name { get; set; }
public DateTime? Year { get; set; }
public int TimePeiod { get; set; }
}
public class University: Organization
{
public string Degree { get; set; }
public string Profession { get; set; }
}
public class Company: Organization
{
public string Website { get; set; }
public string Position { get; set; }
}
So the question is, does data annotation for model validation(both server and client side) work for a model that has composite structure like this? If so, do I just place annotation like I usually do with simple view models? If not, how can I achieve this in alternative ways? Please help.
Any single view model may contain other viewmodels like this:
This model is server side:
[Serializable]
public class MyBigViewModel : IValidatableObject
{
public MyBigViewModel(){
MyOtherViewModel = new MyOtherViewModel();
MyThirdViewModel = new MyThirdViewModel();
}
public MyOtherViewModel {get;set;}
public MyThiddViewModel {get;set;}
public void Post(){
//you can do something here based on post back
//like maybe this where the post method here processes new data
MyOtherViewModel.Post();
}
}
The controller could look like this:
public ActionResult UserList (MyBigViewModel uvm){
if(ModelState.IsValid){
uvm.Post();
return View(uvm);
}
return View(uvm);
}
You can implement the IValidateableObject to do "server side" validation. In the example above however, we want each viewmodel to "contain" it's own model for validation.
Each viewmodel property can use data annotations "contained" in only that viewmodel. It's a very nice way to "Contain" what you want where you want.
I very often use multiple Viewmodels in main VM and pass them in with partial views as needed.

MVC Model doesnt support ToPagedList

I have a model like this
public class SearchVM
{
[DisplayName("Type")]
public string Type { get; set; }
[DisplayName("Beds")]
public string NumberOfBeds { get; set; }
[DisplayName("Baths")]
public string NumberOfBaths { get; set; }
[DisplayName("Prices From")]
public string PriceFrom { get; set; }
[DisplayName("Prices To")]
public string PriceTo { get; set; }
public IEnumerable<Rental> Rentals { get; set; }
public IEnumerable<Sale> Sales { get; set; }
public IEnumerable<Rental> FeatureRentals { get; set; }
public IEnumerable<Sale> FeatureSales { get; set; }
public Rental NewRentals { get; set; }
public Sale NewSales { get; set; }
}
In my controller when trying to use this model SearchVM i cannot use the ToPagedList method
public ActionResult Search(SearchVM searchvm, int page = 1)
{
var query = from c in context.Rentals
select c;
searchvm.Rentals = query;
return View("RentProperty", query.ToPagedList(page,9));
}
I noticed that searchvm.ToPagedList doesnt work. Can some one please help
You are either missing a library reference in your code or if you already have that, you need to add a relevant using statement. For example, you may need this at the top of your code:
using PagedList;
Without this line, the compiler doesn't know where to get the ToPagedList() extension method.

MVC 4 Passing View Model to controller - Using JavaScriptSerializer to Deserialize complex JSON Object

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

Categories