Asp.net 创建操作结果参数字典包含参数的空条目



我没有更改我的代码,它曾经有效,我什至在项目的早期版本中澄清了这一点。但是,我现在收到此错误:

参数字典包含不可为空类型"System.Int32"的参数"recipeID"的空条目,用于"BareCupboard.Controllers.RecipeStepControllers.RecipeStepController"中的方法"System.Web.Mvc.ActionResult Create(Int32, BareCupboard.Models.RecipeStep)"。可选参数必须是引用类型、可为 null 的类型或声明为可选参数。参数名称:参数

我的代码是:

[HttpPost]
    public ActionResult Create(int recipeID, RecipeStep newRecipeStep)
    {
        try
        {
            var recipe = db.Recipes.Single(r => r.recipeID == recipeID);
            recipe.RecipieSteps.Add(newRecipeStep);
            db.SaveChanges();
            return RedirectToAction("Index", "Recipe");
        }
        catch
        {
            return View();
        }
    }

我试过:int?recipeID,但这不起作用。任何可能发生的事情的想法,因为我所能看到的只是神秘主义在这里发挥作用!

检查视图代码以了解参数的顺序。模型活页夹需要它以正确的顺序出现。在那里很容易犯错误。

更新

这是解决此问题的一种方法。创建视图模型,如下所示:

    public class RecipeViewModel
    {
       public int RecipeId { get; set; }
       public RecipeStep RecipeStep { get; set; }
    }

在控制器中,您将拥有以下内容:

    public ActionResult Create()
    {
        var recipeId = 10 // however you want to select that Id
        var recipeViewModel = new RecipeViewModel {RecipeId = 10}
        return View(recipeViewModel);
    }
  [HttpPost]
  public ActionResult Create(int recipeID, RecipeStep newRecipeStep)
  {
     //your code
  }

在视图中,您可以执行以下操作:

@model MvcApplication3.Models.RecipeViewModel
@using (Html.BeginForm(null,null,FormMethod.Post))
{
 <div>
    <p>@Html.HiddenFor(x=>x.RecipeId) </p>
    <p>@Html.TextBox("RecipeStepData1")</p>
     <p>@Html.TextBox("RecipeStepData2")</p>
    <p>@Html.TextBox("RecipeStepData3")</p>
</div>
<input type="submit" value="Submit"  id="btn" /> 
}

请注意顺序。我先输入 id,然后放置其余的配方步骤数据,以便正确绑定。

对于开始表单,您不必在同一页面上发布帖子时指定操作和控制器。如果你放在那里也无妨。

希望这有帮助... :)

为什么 recipeID 在您发布的数据中为空?这是你的问题和 var recipe = db.Recipes.Single(r => r.recipeID == recipeID)无法获得recipeID=null,因为r.recipeID不可为空。

最新更新