我是MVC新手,我对MVC了解不多,所以有时我无法得到错误, 我正在创建双列表框并将 listbox1 的项目移动到 listbox2,在第一个列表框中从数据库中获取数据,因此我创建了以下内容。 模型.cs
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
public string Class { get; set; }
}
ViewModel.cs
public class ViewModel
{
public List<Model> AvailableModel { get; set; }
public List<Model> RequestedModel { get; set; }
public string[] AvailableSelected { get; set; }
public string[] RequestedSelected { get; set; }
}
在 Controller 中从数据库获取数据我创建了以下内容
[NonAction]
private Model getName()
{
var name = (from m in db.Models
select m);
return name;
}
[NonAction]
public List<Model> getAllInstituteNameList()
{
return getName();
}
[HttpGet]
public ActionResult Index()
{
ViewModel model = new ViewModel { AvailableModel = getAllInstituteNameList(), RequestedModel = newList<Model>() };
return View();
}
运行后,抛出以下异常
Cannot implicitly convert type 'System.Linq.IQueryable' to 'DemoListBox.Models.Model'. An explicit conversion exists (are you missing a cast?)
在这条线上
var name = (from m in db.Models
select m);
return name;
请帮忙解决一下......
已更新
按照你的答案后.. 我再次看到这个新的异常
Object reference not set to an instance of an object.
在这一行
<%:Html.ListBoxFor(model =>model.AvailableSelected, newMultiSelectList(Model.AvailableModel, "Id", "Name", Model.AvailableSelected))%>
- 已编辑
查看
<h2>Index</h2>
<%using(Html.BeginForm()) {%>
<div>
<hr/>
<table>
<thead>
<tr>
<th>
Available
</th>
<th>
</th>
<th>
Requested
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<%:Html.ListBoxFor(model =>model.AvailableSelected, newMultiSelectList(Model.AvailableModel, "Id", "Name", Model.AvailableSelected))%>
</td>
<td>
<inputid="add"name="add"type="submit"value=">>"/>
<br/>
<inputid="remove"name="remove"type="submit"value="<<"/>
</td>
<td>
<%:Html.ListBoxFor(model=>model.RequestedSelected,newMultiSelectList(Model.RequestedModel,"Id","Name",Model.RequestedSelected)) %>
</td>
</tr>
</tbody>
</table>
<br/>
<hr/>
</div>
<% }%>
最佳答案
您的 getAllInstituteNameList 需要模型集合(列表)。 您的 getName 返回单个模型(与上述预期类型冲突的内容)。 您的 getName 尝试返回 Collection 但预期结果是单个模型。又一个错误。
[NonAction]
private List<Model>getName()
{
var names = (from m in db.Models
select m).ToList();
return names;
}
[NonAction]
public List<Model> getAllInstituteNameList()
{
return getNames();
}
编辑
将模型返回到 View
return View(model);
关于c# - 无法将类型 'System.Linq.IQueryable<>' 隐式转换为 'Model' 。存在显式转换(是否缺少强制转换?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23403959/