Reputation: 152
I am still new to programming and am working on this project where I got stuck after submitting data to a table in SQL using the entity framework. Although this all works fine, I am struggling returning the record I have just submitted. The challenge for me lies within combining multiple arguments to identify the record.
The goal is to return a record based on UserID and the errandID. My controller looks as follows:
public ActionResult errandPreview()
{
var userID = User.Identity.GetUserId();
var errandID = DB.errandList.Find(userID).ID;
var model = new errands
{
//Title = DB.errandList.Find(errandID).Title.ToString(),
Title = DB.errandList.Where(x => x.ID == errandID).FirstOrDefault().ToString()
};
return View();
}
I am trying to get the UserID from the logged in user and then select the errandID via this attribute to ultimately get to the title of the errand (along with other stuff...) but I just can't get it done. Your help is appreciated!
Upvotes: 1
Views: 28
Reputation: 12304
First off, if you just insert a record you would probably go back to some sort of an Index view with a list. From there you could pass the key as a parameter into the errandPreview action.
Assuming you just want to call some sort of display action:
public ActionResult errandPreview()
{
var userID = User.Identity.GetUserId();
// This assumes 1 errand for a given user
// Otherwise you will need to pass the errandId in as a parameter, ViewBag, etc.
var errandToPreview = DB.errandList
.OrderByDescending(el => el.ID)
.FirstOrDefault(el => el.ID == userID);
if (errandToPreview == null) { // handle error }
// You could just send the errand to the view to display
// return View(errandToPreview);
// Otherwise build a viewmodel
var viewmodel = new ErrandViewModel
{
Title = errandToPreview.Title,
OtherErrandField = errandToPreview.OtherField,
...
};
return View(viewmodel);
}
Upvotes: 1