这是来 self 的 Controller 的代码片段
[HttpPost]
public ActionResult Cancel(string id,FormCollection collection)
{
//This is how I would like to declare appt but I cannot seem to correctly pass id into this method
//var appt = Application.Session.GetObjectFromOid<Appointment>(new ObjectId(id));
//I am trying to do it this way instead but I get an error
var appt = (Appointment)Application.Appointments.Where(a=>a.Id.Equals(collection["Id"]));
.....
}
这是我得到的错误:无法将类型为“WhereListIterator`1[Web.Model.Appointment]”的对象转换为类型“Web.Model.Appointment”。
这是我的观点:
<input type="button" value="Save" onclick="updateCancel(); return false;" /><button>Save</button>
这是我的职责
function updateCancel() {
$('#cancel').ajaxSubmit({
});
}
那么为什么我会收到此错误? 或者有没有办法将 Model.Data.Id 传递到我的函数中,以便我可以只使用 id?
最佳答案
Where 子句返回一个迭代器。选择您要使用的内容。即,如果您只期望一个结果,则可以使用 FirstOrDefault
。您还可以使用索引,例如 [1]
。
var appt = (Appointment)Application.Appointments.Where
(a=>a.Id.Equals(collection["Id"]))
.FirstOrDefault();
请注意,FirstOrDefault
在未找到项目时返回 null
,因此请务必检查结果值。
PS:你可能不需要你的类型转换。如果没有 (Appointment
,从您的标题中的错误来看,这应该可以正常工作,因为列表中的项目属于 Appointment
类型。
关于c# - 无法转换类型为 'WhereListIterator` 的对象 1[Web.Model.Appointment ]' to type ' Web.Model.Appointment',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9625955/