Radioactive Coffe
Radioactive Coffe

Reputation: 155

Retrieve Certain Data From DB and Send It To View

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           |

Upvotes: 0

Views: 32

Answers (1)

user3559349
user3559349

Reputation:

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);
}

Upvotes: 1

Related Questions