c# - 无法转换类型为 'WhereListIterator` 的对象 1[Web.Model.Appointment ]' to type ' Web.Model.Appointment'

标签 c# asp.net-mvc-2

这是来 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/

相关文章:

javascript - 从 RouteUrl 获取完整的 url

c# - 在 Controller 外调用 return RedirectToAction ("Activity")

jquery - JQGrid加载下拉列表数据

c# - 如何从 C# 作为 MT4 dll 连接到 Mysql?

c# - 如何更改 ComboBox 下拉按钮颜色

c# - 尝试导出 X509 私钥的 RSAParameters 时出现 CryptographicException "Key not valid for use in specified state."

c# - 在 MVC2 中显示图像 blob

json - JQuery.Ajax 调用 Asp.Net MVC JsonResult 给出 12031 错误,Json webservice 工作正常

asp.net-mvc-2 - ASP.NET Mvc - 可为空参数和逗号作为分隔符

c# - 从调试版本中的类型获取文件的源代码文件名