我试图将一个参数传递给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上出现错误,说{“对象引用未设置为对象的实例”} –