0

Problem

This obviously doesn't work since it was a shot in the dark, What's the best way to retrieve data with certain id and then send/display data to view

Model

public partial class Profile { public int Id { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } } 

Controller

public ActionResult Details() { ProfileContext db = new ProfileContext(); var data = (from c in db.Profiles where c.Id == 1 select c).ToString(); return View(data); } 

View

 @model Learning4.Profile @{ ViewBag.Title = "Details"; } <h2>Details</h2> <div> <h4>Profile</h4> <hr /> <dl class="dl-horizontal"> <dt> @Html.DisplayNameFor(model => model.Firstname) </dt> <dd> @Html.DisplayFor(model => model.Firstname) </dd> <dt> @Html.DisplayNameFor(model => model.Lastname) </dt> <dd> @Html.DisplayFor(model => model.Lastname) </dd> </dl> </div> 

Data

|Id |Firstname |Lastname |
|1  |John           |Doe           |

1
  • Replace .ToString() with .FirstOrDefault() Commented Dec 10, 2016 at 6:27

1 Answer 1

1

Your wanting to return a single object so you need to use .FirstOrDefault() (your query returns a collection, even through it may contain only one element)

public ActionResult Details() { ProfileContext db = new ProfileContext(); var data = (from c in db.Profiles where c.Id == 1 select c).FirstOrDefault(); // or data = db.Profiles.FirstOrDefault(x => x.Id == 1); return View(data); } 
Sign up to request clarification or add additional context in comments.

2 Comments

if I wanted to only retrieve one piece of data for example Firstname only, is there a possibility I can send it through a viewbag.Firstname ? would .FirstOrDefault() do the trick?
string data = db.Profiles.Where(x => x.Id == 1).Select(x => x.FirstName); will return just the value of the FirstName

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.