我試圖將一個參數傳遞給Index視圖中的Create @ Html.ActionLink,但是我遇到了一些困難。將參數傳遞給Html.ActionLink
我有一個地址控制器,用戶在訪問索引視圖時可以看到特定人員的地址。我想將此PersonID傳遞給「創建」視圖,以便他們在創建新地址時不必選擇或輸入該人員。我的ActionLink的是這樣的 -
@Html.ActionLink("Create New", "Create", new { id = Model.[PersonID is not a choice]})
我的問題是,經過模型是PersonID是不是一種選擇。我不知道如何將PersonID獲取到AddressController中的Create函數。
我試着跟着帖子 - Passing a parameter to Html.ActionLink when the model is IEnumerable<T> - 他們有同樣的問題。第一個答案看起來像是一個可能的解決方案,但是我無法複製他們創建的模型,並且當我將這些部分放入Address模型中時,我無法複製他們在控制器中執行的代碼。還有其他解決方案嗎?
我的地址模式 -
public partial class Address
{
public int AddressID { get; set; }
public int PersonID { get; set; }
[Display(Name="Address")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
public string Address2 { get; set; }
public string City { get; set; }
[Display(Name="State")]
public string StateAbbr { get; set; }
[Display(Name = "Zip Code")]
public string Zip { get; set; }
public virtual Person Person { get; set; }
public List<Address> Address { get; set; }
}
我AddressController指數
public ActionResult Index(int id)
{
var addresses = db.Addresses.Include(a => a.Person)
.Where(a => a.PersonID == id);
Person person = db.People.Find(id);
ViewBag.FullName = person.FirstName + " " + person.LastName;
person.PersonID = id;
return View(addresses.ToList());
}
地址索引視圖 -
@model IEnumerable<OpenBurn.Models.Address>
@{
ViewBag.Title = "Address";
}
<h2>Address</h2>
<p>
@Html.ActionLink("Create New", "Create", new { id = .PerosnID })
</p>
<h3 style="color: #008cba;"> @ViewBag.FullName </h3>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Address1)
</th>
<th>
@Html.DisplayNameFor(model => model.Address2)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.StateAbbr)
</th>
<th>
@Html.DisplayNameFor(model => model.Zip)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Address1)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address2)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.StateAbbr)
</td>
<td>
@Html.DisplayFor(modelItem => item.Zip)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.AddressID }) |
@Html.ActionLink("Details", "Details", new { id=item.AddressID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.AddressID })
</td>
</tr>
}
</table>
感謝信。一切看起來都不錯,但是我在#Html.ActionLink for Create中得到了一個紅色的下標。它說 - 'object'不包含'id'的定義 –
你確定你的語法是這樣的:'@ Html.ActionLink(「Create New」,「Create」,new {id = Model.PersonID}) '而不是像這樣:'@ Html.ActionLink(「Create New」,「Create」,new object {id = Model.PersonID})'? – ekad
就是這樣。這對我有幫助和自動完成。當我嘗試運行它時遇到了錯誤 - 當它試圖訪問Index視圖時,它在Model.Addreses的@foreach上出現錯誤,說{「對象引用未設置爲對象的實例」} –