我在后端有两个表 Users 和 Expenses。 UserId 是 Expenses 表的外键。我需要将 UserId 从 Usercontroller 传递到 ExpenseController,以根据用户 ID 保存费用信息。但是有两个问题。
- 我无法使用传递给费用 Controller 的 id 参数
- 另一个用于创建费用表,我在其中找不到任何 userId 字段 我要用来节省开支的表格。所以总是有 modelstate.isvalid == false。
请看下面的代码。希望你能帮助我。
//用户 Controller
public ActionResult Index()
{
return View(db.Users.ToList());
}
//Inedx View (用户)
<%= Html.ActionLink("Expenses", "Index", "Expense", new { id=item.Id}, null)%>
//费用 Controller
public ActionResult Index(int id)
{
ViewData["id"] = id;
return View(db.Expenses.Where(x => x.Users.Id == id).ToList());
}
//索引 View (费用)
<%= Html.ActionLink("Create New", "Create", new { id=ViewData["id"]})%>
//费用 Controller (创建)
public ActionResult Create(int id)
{
//ViewData["id"] = id;
return View();
}
//创建 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);
}
}
最佳答案
我认为达成共识的正确方法是为每个 View 构建特定模型,并使用 View 所需的数据填充该模型,包括任何操作可能需要的数据 View 调用。因此,例如,您有一个您的 Create View 将采用的费用模型,其中包含的内容之一是费用的关联用户 ID。处理帖子的 Create 操作将采用费用模型,而不是 FormCollection,作为它的参数。在您的创建 View 中,您会将模型中的用户 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" ) %>
...
<% } %>
关于asp.net - ASP MVC外键提交问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1734223/