c# - Selecting a single record to display on a view -
i have controller user can add friends. actionmethods in controller are:
[authorize] public actionresult add (string id = "") { var model = _db.users .orderby(r => r.username) .where(r => r.id == id).tolist() .select(r => new friendslist { requesterid = httpcontext.user.identity.getuserid().tostring(), requesteeid = id, username = r.username, status = "newrequest", requestdate = datetime.now, acknowledgedate = datetime.now }); return view(model); } [httppost] [validateantiforgerytoken] public actionresult add (friendslist friendslist) { if (modelstate.isvalid) { _friend.entry(friendslist).state = system.data.entity.entitystate.modified; _friend.savechanges(); return view(friendslist); } }
and view code looks like:
@model max.models.social.friendslist <h2>add</h2> <div> @model.id = @model.id; @model.requesteeid = @model.requesteeid; @model.status = @model.status; @model.username = @model.username; @model.requesterid = @model.requesterid; <p>add @model.username ?<input type="submit" value="add" /></p> </div>
i not sure how data passed controller post add...but best guess.
when said , done, error server:
the model item passed dictionary of type 'system.linq.enumerable+whereselectlistiterator`2[max.models.applicationuser,max.models.social.friendslist]', dictionary requires model item of type 'max.models.social.friendslist'.
why error?
your add action method selects 1 user database model
, type system.linq.enumerable+whereselectlistiterator'2[max.models.applicationuser,max.models.social.friendslist]
, while view accepts max.models.social.friendslist
.
so need select 1 record. can using firstordefault()
:
[authorize] public actionresult add (string id = "") { var model = _db.users .orderby(r => r.username) .where(r => r.id == id).tolist() .select(r => new friendslist { requesterid = httpcontext.user.identity.getuserid().tostring(), requesteeid = id, username = r.username, status = "newrequest", requestdate = datetime.now, acknowledgedate = datetime.now }) .firstordefault(); if (model == null) { // handle not found } return view(model); }
Comments
Post a Comment