我在后端有两个表用户和费用。 UserId是Expenses表的foreignKey。我需要将UserId从Usercontroller传递给ExpenseController,以便根据用户ID保存费用信息。但是有两个问题。
请查看以下代码。希望你能帮帮我。
// 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);
}
}
答案 0 :(得分:7)
我认为达成共识正确的方法是为每个视图构建特定模型,并使用视图所需的数据填充该模型,包括可能需要的任何操作所需的数据视图调用。因此,例如,您有一个您的创建视图将采用的费用模型,其中包含的内容之一将是费用的关联用户ID。处理帖子的Create操作将采用费用模型而不是FormCollection作为其参数。在“创建视图”中,您可以将模型中的用户ID存储在隐藏字段中,以便将其值传播回帖子。
[AcceptVerbs( HttpVerbs.Get )]
public ActionResult Create(int id)
{
return View( new ExpenseModel { UserId = id } );
}
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Create( ExpenseModel expense )
{
...
}
查看
... Inherits="System.Mvc.ViewPage<ExpenseModel>" %>
<% using (Html.BeginForm()) { %>
<%= Html.Hidden( "UserId" ) %>
...
<% } %>