如何从Razor Html.Form传递选定的值作为路由参数

时间:2015-11-10 18:54:05

标签: asp.net-mvc razor

如何将选定的值/对象/项目从数据列表传递给控制器​​作为参数?

以下是我的表单的剃刀代码:

@using (Html.BeginForm("Details", "Recipes")) {
    <input type="search" list=@Model.Recipes autocomplete="on" id="RecipeId"/>
    <datalist id=@Model.Recipes>
        @foreach (var item in Model.Recipes) {
            <option name = @item.RecipeId>@item.Name</option>
            <option value=@item.RecipeId></option>
        }
    </datalist>
    <input type="submit">
}

以下是渲染时的外观: enter image description here

最后是控制器:

// GET: Recipes/Details/5
public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    RECIPE rECIPE = db.RECIPE.Find(id);
    if (rECIPE == null)
    {
        return HttpNotFound();
    }
    return View(rECIPE);
}

提前致谢

1 个答案:

答案 0 :(得分:2)

您应该设置input name属性,以便在发布时如何区分请求中的表单值:

<input name="id" type="search" list=@Model.Recipes autocomplete="on" id="RecipeId"/>