我在后端有两个表用户和费用. UserId是Expenses表的foreignKey.我需要将UserId从Usercontroller传递给ExpenseController,以便根据用户ID保存费用信息.但是有两个问题. 我无法使用传递给费用控制器的
>我无法使用传递给费用控制器的id参数
>另一个是创建费用表单,我找不到任何userId字段
我要用来节省开支的形式.所以总是有modelstate.isvalid == false.
请查看以下代码.希望您能够帮助我.
// UserController的
public ActionResult Index() { return View(db.Users.ToList()); }
// Inedx View(用户)
<%= 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); } }我认为,达成共识的正确方法是为每个视图构建特定模型,并使用视图所需的数据填充该模型,包括视图调用的任何操作可能需要的数据.因此,例如,您有一个您的创建视图将采用的费用模型,其中包含的内容之一将是费用的关联用户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" ) %> ... <% } %>