072et
072et

Reputation: 345

How to display item from database as a label text in asp.net mvc 4

So I am trying to show some text that i retrieved from the database and wanted to show them as a label or just show up on a page. I am having trouble displaying this text and here is what i have:

controller:

public ActionResult _StudentName(int id)
    {
        id = 12;
        var model = new StudentNameModel();
        using (var db = new School())
        {
            var result = from s in db.Students
                         where s.ID == id
                         select s.StudentName;
            model.StudentName = result.ToString();
        }
        return View(model);
    }

My Model:

public class StudentNameModel
{
    [Display(Name = "Student Name")]
    public string StudentName { get; set; }
}

My view:

    @model Adams.Models.StudentNameModel
     <fieldset>
     @Html.LabelFor(m => m.StudentName)
     @Html.TextBoxFor(m => m.StudentName)
</fieldset>

Upvotes: 2

Views: 11850

Answers (1)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60503

seems you just need

@Html.DisplayFor(m => m.StudentName)

instead of

@Html.TextBoxFor(m => m.StudentName)

by the way, change your query to something like

var studentName = (from s in from s in db.Students
                         where s.ID == id
                         select s.StudentName)
                  .FirstOrDefault();
if (student != null)
   model.StudentName = studentName;

Upvotes: 4

Related Questions