This is a code fragment from my 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"]));
.....
}
This is the error that I get:Unable to cast object of type 'WhereListIterator`1[Web.Model.Appointment]' to type 'Web.Model.Appointment'.
This is my view:
<input type="button" value="Save" onclick="updateCancel(); return false;" /><button>Save</button>
and this is my function
function updateCancel() {
$('#cancel').ajaxSubmit({
});
}
So why am I getting this error? OR is there a way to pass Model.Data.Id into my function so that I can just use id instead?
The Where-clause returns an iterator. Select what you want to use instead. I.e., if you expect only one result, you can use FirstOrDefault
. You can also use an index, like [1]
.
var appt = (Appointment)Application.Appointments.Where
(a=>a.Id.Equals(collection["Id"]))
.FirstOrDefault();
Note that FirstOrDefault
returns null
when the item is not found, so be sure to check the result value.
PS: you probably don't need your cast there. Without (Appointment
, from the error in your title, this should just work, because the items in the list are of type Appointment
.
This is what I ended up using and it worked.
var appt = Application.Session.GetObjectFromOid<Appointment>(new ObjectId(id));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With