I am trying to write a simple web application which displays certain details dependent on which ID is picked from a select list.
I can get the data from the database using the following:
Class:
namespace InterviewTest.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Widget")]
public partial class Widget
{
public int WidgetID { get; set; }
[Required]
[StringLength(50)]
public string WidgetName { get; set; }
[Required]
public string WidgetDescription { get; set; }
public int WidgetColourID { get; set; }
}
}
Controller:
using System.Linq;
using System.Web.Mvc;
using InterviewTest.Models;
namespace InterviewTest.Controllers
{
public class HomeController : Controller
{
WidgetConn db = new WidgetConn();
public virtual ActionResult Index(Widget widget)
{
var widgets =
(from w in db.Widgets
where w.WidgetID == 1
select new
{
WidgetName = w.WidgetName,
WidgetDescription = w.WidgetDescription,
WidgetColourID = w.WidgetColourID
}).ToList();
var data = widgets[0];
return View(data);
}
}
}
The data returned in 'data' is returned as:
WidgetID 1 WidgetDescription Test WidgetColourID 1
Test View:
@model InterviewTest.Models.Widget
@{
ViewBag.Title = "test";
}
<h2>test</h2>
<div>
<h4>Widget</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.WidgetName)
</dt>
<dd>
@Html.DisplayFor(model => model.WidgetName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.WidgetDescription)
</dt>
<dd>
@Html.DisplayFor(model => model.WidgetDescription)
</dd>
<dt>
@Html.DisplayNameFor(model => model.WidgetColourID)
</dt>
<dd>
@Html.DisplayFor(model => model.WidgetColourID)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.WidgetID }) |
@Html.ActionLink("Back to List", "Index")
</p>
When I try to us @Html.DisplayNameFor(model => model.WidgetName) to display the data returned I get the error:
htmlhelper does not contain a definition for DisplayNameFor and no extension method DisplayNameFor accepting a first argument of type 'HTMLHelper' could be found. Are you missing an assembley or reference?
I read that I should have 'using System.Web.Mvc.HtmlHelper;' however this appears to be a namespace so cannot be used in this way. Changing my namespace means I can no longer access this class.
I also read that System.Web.Mvc.Html should containt the 'HtmlHelper' but using this has not resolved my issue.
My questions are:
1: Should I be using @Html.DisplayNameFor(model => model.WidgetName) with a .cshtml file or is there another way to access the data?
2: If the way I am trying to access the data is correct, how/where do I add the namespace so I can access the HtmlHelper namespace.
3: If the the way I am trying to access the data is NOT correct for a .cshtml file please could someone point me to some documentation I could read?
Thanks.