3
我有兩個表用戶和費用在後端。 UserId是Expenses表的外鍵。我需要將UserId從Usercontroller傳遞到ExpenseController,以節省用戶ID的費用信息。但是有兩個問題。ASP MVC外鍵提交問題
- 我無法使用傳送到費用控制
- 另一種是爲創建費用的形式,我找不到任何用戶id字段中 形式對我正要去id參數節省費用。所以總是有modelstate.isvalid == false。
請看下面的代碼。希望您能夠幫助我。
// UserController中
public ActionResult Index()
{
return View(db.Users.ToList());
}
// Inedx視圖(用戶)
<%= Html.ActionLink("Expenses", "Index", "Expense", new { id=item.Id}, null)%>
// ExpenseController
public ActionResult Index(int id)
{
ViewData["id"] = id;
return View(db.Expenses.Where(x => x.Users.Id == id).ToList());
}
//索引視圖(費用)
<%= Html.ActionLink("Create New", "Create", new { id=ViewData["id"]})%>
// 費用控制器(創建)
public ActionResult Create(int id)
{
//ViewData["id"] = id;
return View();
}
//創建視圖
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="ExpenseTitle">ExpenseTitle:</label>
<%= Html.TextBox("ExpenseTitle") %>
<%= Html.ValidationMessage("ExpenseTitle", "*") %>
</p>
<p>
<label for="ExpenseDescription">ExpenseDescription:</label>
<%= Html.TextBox("ExpenseDescription") %>
<%= Html.ValidationMessage("ExpenseDescription", "*") %>
</p>
<p>
<label for="Date">Date:</label>
<%= Html.TextBox("Date") %>
<%= Html.ValidationMessage("Date", "*") %>
</p>
<p>
<label for="Expense">Expense:</label>
<%= Html.TextBox("Expense") %>
<%= Html.ValidationMessage("Expense", "*") %>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
//創建帖子
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
var expense = new Expenses();
try
{
TryUpdateModel(expense, new string[] {"UserId", "ExpenseTitle", "ExpenseDescription", "Date", "Expense" }, collection.ToValueProvider());
if (ModelState.IsValid)
{
db.AddToExpenses(expense);
db.SaveChanges();
return RedirectToAction("Index",int.Parse(collection["UserId"]));
}
else {
return View(expense);
}
}
catch
{
return View(expense);
}
}
謝謝您的回答 – FlintOff 2009-11-14 13:49:24
@ASP MVC - 歡迎您。由於您是新來賓,我只想指出系統的工作方式是使用每個答案頂部的投票計數旁邊的向上/向下箭頭(一旦您有足夠的點數),您就可以獲得有用的答案,並通過使用投票計數下方的複選標記接受最能回答您問題的問題。歡迎來到這個網站。 – tvanfosson 2009-11-14 13:59:04