![](/img/trans.png)
[英]Use viewmodel to bind data with html.dropdownlistFor in asp.net-MVC
[英]How to bind anonymous type to viewModel in ASP.NET-MVC
我需要将匿名类型输出绑定到viewmodel才能在视图上传递它。 我需要将复选框与模型值绑定在一起,我正在使用join来获取值,但不知道如何将其传递给视图。 我的加入查询是
var v = (from pd in ge.Costs
join od in ge.Services on pd.ServiceId equals od.ServiceId
join ct in ge.ServiceTypes on pd.ServiceTypeId equals ct.ServiceTypeId
where pd.ServiceTypeId.Equals(2)
select new
{
pd.CostId,
od.serviceName,
ct.ServiceTypeValue,
pd.ServiceCost
}).ToList();
我的viewModel是
public class costViewModel
{
public int CostId { get; set; }
public string serviceName { get; set; }
public string ServiceTypeValue { get; set; }
public string ServiceCost { get; set; }
}
我需要将CostId,serviceName,ServiceTypeValue,ServiceCost绑定到视图模型以在视图中传递它
在视图上检索模型是
@foreach (var item in Model)
{
<input type="checkbox" name="@item.serviceName" id="@item.serviceName" value="@item.ServiceCost">@item.
}
请帮忙。
不要让您的选择查询匿名,只需将您的选择与viewModed一起传递
var v = (from pd in ge.Costs
join od in ge.Services on pd.ServiceId equals od.ServiceId
join ct in ge.ServiceTypes on pd.ServiceTypeId equals ct.ServiceTypeId
where pd.ServiceTypeId.Equals(2)
select new costViewModel()
{
CostId = pd.CostId,
serviceName = od.serviceName,
ServiceTypeValue = ct.ServiceTypeValue,
ServiceCost = pd.ServiceCost
}).ToList();
view(v);
然后在视图模型中传递v
并在查看页面上使用
@model IEnumerable<project.ViewModel.costViewModel>
尝试使用costViewModel
将值传递到您的View中,因此,简而言之,不要让您的select
匿名,创建一些所需的对象并将v
传递给View:
在您的控制器中:
var v = (from pd in ge.Costs
join od in ge.Services on pd.ServiceId equals od.ServiceId
join ct in ge.ServiceTypes on pd.ServiceTypeId equals ct.ServiceTypeId
where pd.ServiceTypeId.Equals(2)
select new costViewModel()
{
CostId = pd.CostId,
serviceName = od.serviceName,
ServiceTypeValue = ct.ServiceTypeValue,
ServiceCost = pd.ServiceCost
}).ToList();
return View(v);
并在您的视图中:
@model List<costViewModel>
var v = (from pd in ge.Costs
join od in ge.Services on pd.ServiceId equals od.ServiceId
join ct in ge.ServiceTypes on pd.ServiceTypeId equals ct.ServiceTypeId
where pd.ServiceTypeId.Equals(2)
select new costViewModel
{
CostId = pd.CostId,
serviceName = od.serviceName,
ServiceTypeValue = ct.ServiceTypeValue,
ServiceCost = pd.ServiceCost
}).ToList();
或匿名
var v = (from pd in ge.Costs
join od in ge.Services on pd.ServiceId equals od.ServiceId
join ct in ge.ServiceTypes on pd.ServiceTypeId equals ct.ServiceTypeId
where pd.ServiceTypeId.Equals(2)
select new
{
CostId = pd.CostId,
serviceName = od.serviceName,
ServiceTypeValue = ct.ServiceTypeValue,
ServiceCost = pd.ServiceCost
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.