【问题标题】:Using the value from a previous view in the current view在当前视图中使用前一个视图的值
【发布时间】:2019-09-06 09:07:45
【问题描述】:

长话短说;我有 2 个表(RecipeRecipeIngredient),由外键 recipeId 关联。在我的 MVC 中,如果我想查看食谱的成分,我按下“Ingredients”,然后会出现一个包含该特定食谱成分的新视图。

Index.cshtml(配方)

@Html.ActionLink("Edit", "CreateOrEdit", "Recipe", new { id = item.id })
@Html.ActionLink("Delete", "Delete", "Recipe", new { id = item.id })
@Html.ActionLink("Ingredients", "Index", "RecipeIngredient", new { recipeId = item.id })

问题出现在这里;如果我想添加新的成分,我会点击“添加成分”操作链接,会弹出一个表单

AddIngredient.cshtml(配方成分)

<p>
    @Html.ActionLink("Add ingredient", "AddIngredient", "RecipeIngredient", new { Recipe recipeId })
</p>

新的 { 食谱 recipeId }

我尝试了这个想法,我将能够导入以前用于访问某个配方的成分的变量。

如上图所示,我的任务是使用先前访问的配方的 ID 自动生成 recipeId 字段。有什么建议吗?

【问题讨论】:

  • 是否要将新创建的成分与当前配方关联起来?
  • 是的,这就是我愿意做的。新创建的成分应该具有当前配方的 recipeId。
  • 让您的操作链接如下:@Html.ActionLink("Add ingredient","AddIngredient", "RecipeIngredient", new { id = recipeId }) 并在您的控制器中:public AddIngredientDelete(int id) {//Your logic}
  • @RahulSharma 关键是 id 将是 RecipeIngredient 的 ID,而我需要 Recipe 的 ID,它是 RecipeIngredient 的外键,称为“recipeId”。我尝试在 @ 模型中使用元组,但随后出现更多错误,并且解决方案并不像我想象的那么简单,因为我必须删除很多东西并重新做。
  • @Questieme 那么在这种情况下,您需要创建一个ViewModel,您将在其中关联来自数据库的这些值。基本上我的观点是,您需要在 Controller 中建立此关联,然后使用具有此关联的模型渲染您的视图。

标签: c# html model-view-controller


【解决方案1】:

您可以使用 TempData,在用户导航到 Recipie 时设置它并在 AddIngredient 中读取它。

【讨论】:

  • 感谢您的提示!我会试一试的。
猜你喜欢
  • 2012-09-08
  • 2012-05-16
  • 1970-01-01
  • 2014-11-14
  • 2011-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
相关资源
最近更新 更多