Reputation: 14688
My model class is:
public class Contracts
{
public int ContractId { get; set; }
public string contract { get; set; }
}
Add its controller:
public ActionResult Index()
{
var contracts = from c in db.Contracts
select c;
return View(contracts.ToList());
}
The strongly typed view returns:
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
<td>
@item.ContractId
</td>
<td>
@item.contract
</td>
</tr>
}
Originally the base table's primary key was called ID. Then I changed it to ContractId for usage in foreign-keys.
How do I set the models primary key so that the view will recognize it?
UPDATE1: I am using EntityFramework 4
UPDATE2: The answer provided by Brian does correctly assign the key manually. To solve my problem required renaming the table to 'Contracts' from 'contract'. I also renamed the 'contract' field in that table to 'Name'. Then I deleted the 'Contracts' model class and recreated it as 'Contract'. The VIEW folder was renamed to Contract. My guess is the naming conventions were breaking the code recognition of the primary key.
Upvotes: 2
Views: 3901
Reputation: 5534
Assuming your action methods on the controller something like this:
public ActionResult Details(int id){
// retrieve contract and generate view
}
public ActionResult Edit(int id){
// retrive contract and generate view
}
public ActionResult Delete(int id){
// delete contract
}
Then your view should look like this:
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ContractId }) |
@Html.ActionLink("Details", "Details", new { id=item.ContractId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ContractId })
</td>
<td>@item.ContractId</td>
<td>@item.contract</td>
</tr>
}
Upvotes: 3