我对MVC和C#很新,我发现自己陷入了这个问题。
我有3个表: UserCredentials , BusinessCredentials 和 BusinessDetails 。 我创建了3个ViewModel:
UserBusinessListingViewModel
[Display(Name = "User Id:")]
public int User_Id { get; set; }
public IEnumerable<BusinessCredentialsViewModel> BusinessCredentialsViewModels {get; set;}
BusinessCredentialsViewModel
[Display(Name = "Business Id:")]
public int Id { get; set; }
[Display(Name = "Name:")]
public string Name { get; set; }
public IEnumerable<BusinessDetailsViewModel> BusinessDetailsViewModels { get; set; }
BusinessDetailsViewModel 即可。
[Display(Name = "Id:")]
public int Id { get; set; }
[Display(Name = "Category:")]
public string Category { get; set; }
[Display(Name = "Rating:")]
public float Rating { get; set; }
[Display(Name = "Country:")]
public string Country { get; set; }
[Display(Name = "State:")]
public string State { get; set; }
[Display(Name = "City:")]
public string City { get; set; }
主视图模型是 UserBusinessListingViewModel ;它必须显示上面所有3个表中的信息。
在控制器中我有
UserCredential businessSectionUserCredential =
_unitOfWork.UserCredentials
.Include("BusinessCredentials")
.Include("BusinessCredentials.BusinessDetails")
.First(p => p.Id == WebSecurity.CurrentUserId);
var userBusinessListingViewModel = new UserBusinessListingViewModel();
userBusinessListingViewModel.User_Id = businessSectionUserCredential.Id;
我被困在这里。
userBusinessListingViewModel.BusinessCredentialsViewModels
没有属性。我该如何映射?
谢谢。
我想实现这样的目标。 之前已完成此操作,但这很简单,因为我只有一个视图模型:
var profileViewModel = new ProfileViewModel();
UserCredential userCredential = _unitOfWork.UserCredentials.Include(p => p.UserDetail).First(p => p.Id == WebSecurity.CurrentUserId);
UserDetail userDetail = userCredential.UserDetail;
profileViewModel.UserCredentials_Id = userCredential.Id;
profileViewModel.Email = userCredential.Email;
profileViewModel.FirstName = userDetail.FirstName;
profileViewModel.LastName = userDetail.LastName;
return PartialView("_ProfilePartial", profileViewModel);
我正在使用
@model BusinessListing.ViewModels.UserBusinessListingViewModel
<div class="col-md-8">
<p class="p-custom-bg">@Model.User_Id</p>
</div>
显示此内容。
答案 0 :(得分:2)
Add
您没有BusinessCredentialsViewModels
或类似的任何方法,因为它是IEnumerable
。但是,你已经为它定义了一个getter和setter,所以你可以这样做:
userBusinessListingViewModel.BusinessCredentialsViewModels = array;
在不知道更多代码的情况下,我无法告诉您要编写的确切代码。但是说UserCredential
的属性BusinessCredientials
是IEnumerable<BusinessCredential>
,您可以这样做:
userBusinessListingViewModel.BusinessCredentialsViewModels
= userCredential.BusinessCredentials.Select(
x => new BusinessCredentialsViewModel
{
Id = x.Id,
/* etc, etc */
});
答案 1 :(得分:0)
userBusinessListingViewModel.BusinessCredentialsViewModels是IEnumerable,因此您看不到属性。
创建BusinessCredentialsViewModel的对象,然后为其属性指定值。为对象的所有属性分配值后,将其添加到userBusinessListingViewModel.BusinessCredentialsViewModels。例如:
var businessCredentialsViewModel = new BusinessCredentialsViewModel();
businessCredentialsViewModel.Name = "SomeName"; userBusinessListingViewModel.BusinessCredentialsViewModels.Add(businessCredentialsViewModel);