C# 复选框实现
我想为我的在线投票设置一个复选框,其中一个复选框包含选民可以投票给特定候选人的候选人 下面是我的代码 候选视图模型.csC# 复选框实现,c#,asp.net-mvc,C#,Asp.net Mvc,我想为我的在线投票设置一个复选框,其中一个复选框包含选民可以投票给特定候选人的候选人 下面是我的代码 候选视图模型.cs public class CandidatesViewModel { public IEnumerable<candidates> AvailableCandidates { get;set; } public IEnumerable<Candidates> SelectedCandidates { get; set; } pu
public class CandidatesViewModel
{
public IEnumerable<candidates> AvailableCandidates { get;set; }
public IEnumerable<Candidates> SelectedCandidates { get; set; }
public PostedCandidates PostedCandidates { get; set; }
}
public class PostedCandidates
{
public string[] CandidatesId { get; set; }
}
public class Candidates
{
public int candidates_info_id { get; set; }
public string candidates_fullname { get; set; }
public object Tags { get; set; }
public bool IsSelected { get; set; }
}
控制器
public ActionResult Votation(PostedCandidates PostedCandidates)
{
return View();
}
查看
@Html.CheckBoxListFor(x => x.PostedCandidates.CandidatesId,
x => x.AvailableCandidates,
x => x.candidates_info_id,
x => x.candidates_fullname,
x => x.SelectedCandidates)
但当我尝试运行此代码时,显示了一个错误:
'System.Collections.Generic.IEnumerable'
不包含“PostedCandidates”的定义,并且没有扩展名
方法“PostedCandidates”接受类型为的第一个参数
'System.Collections.Generic.IEnumerable'
无法找到(是否缺少using指令或程序集
参考?)
您正在声明类型为
IEnumerable
的模型,并像使用实例而不是集合一样使用它
您需要将模型声明更改为以下内容(假设您将CandidatesViewModel类型的单个实例传递给控制器中的view):
或者,您可以将复选框列表生成更改为类似以下内容(假设您将集合从控制器传递到视图,并且该集合只有一个元素)
尽管我建议您使用变更模型声明
更新
我还注意到您没有将视图模型的实例传递给视图
public ActionResult Votation(PostedCandidates PostedCandidates)
{
CandidatesViewModel vm = new CandidatesViewModel();
//process or fill your viewmodel here.
return View(vm);
}
更改VotationPost的参数名称,为整个视图显示代码。我认为问题在于您没有发布在此处的代码。@model IEnumerableI在我的视图中添加以下内容:@modelIEnumerable@usingMvcCheckBoxList.model当我运行程序时,它返回一个空值。@JenalynParagados,因为我的答案假设您需要将viewmodel的实例传递给视图<代码>CandidatesViewModel vm=新CandidatesViewModel()然后将该viewmodel的实例传递给view方法,如
返回视图(vm)代码>。CheckBoxFor是否应为布尔类型值?
@Html.CheckBoxListFor(x => x.FirstOrDefault().PostedCandidates.CandidatesId,
x => x.FirstOrDefault().AvailableCandidates,
x => x.FirstOrDefault().candidates_info_id,
x => x.FirstOrDefault().candidates_fullname,
x => x.FirstOrDefault().SelectedCandidates)
public ActionResult Votation(PostedCandidates PostedCandidates)
{
CandidatesViewModel vm = new CandidatesViewModel();
//process or fill your viewmodel here.
return View(vm);
}