【发布时间】:2011-12-01 10:58:58
【问题描述】:
我在后端有两个表用户和费用。 UserId 是 Expenses 表的外键。我需要将 UserId 从 Usercontroller 传递到 ExpenseController 以根据用户 ID 保存费用信息。但是有两个问题。
- 我无法使用传递给费用控制器的 id 参数
- 另一个是创建费用表单,我在 我要节省费用的表格。所以总会有modelstate.isvalid == false。
请看下面的代码。希望你能帮助我。
//用户控制器
public ActionResult Index()
{
return View(db.Users.ToList());
}
// Inedx 视图(用户)
<%= Html.ActionLink("Expenses", "Index", "Expense", new { id=item.Id}, null)%>
// 费用控制器
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);
}
}
【问题讨论】:
标签: asp.net asp.net-mvc