ASP.NET MVC通过参数将参数传递给控制器

时间:2016-03-16 16:56:57

标签: c# asp.net-mvc

我在控制器中传递参数时遇到问题。

我在id中获得public ActionResult AddIngridient(int id = 0)值,我需要在public ActionResult AddIngridient(Ingredients ingridients) IngredientID中传递它。怎么做?

我有模特:

public partial class Ingredients
{
    public int IngredientID { get; set; }
    public Nullable<int> AmountID { get; set; }
    public Nullable<int> IngredientTypeID { get; set; }
}

和控制器:

public ActionResult AddIngridient(int id = 0)
    {
        IEnumerable<Ingredient> ListOfIngridient =  FRE.Ingredient.Select(key => key).ToList();
        ViewBag.IngridientsList = new SelectList(ListOfIngridient,"IngredientID", "IngredientName");

        IEnumerable<Amount> ListOfAmounts = FRE.Amount.Select(key => key).ToList();
        ViewBag.AmountsList = new SelectList(ListOfAmounts, "AmountID", "AmountName");

        ViewBag.ID = id;
        return View();
    }
    [HttpPost]
    public ActionResult AddIngridient(Ingredients ingridients)
    {
        return View();
    }

视图如下:

@model FoodRecipes.Models.Ingredients
@{
ViewBag.Title = "AddIngridient";
}

<h2>AddIngridient</h2>
@using(Html.BeginForm())
{ 
@Html.DropDownListFor(model => model.IngredientTypeID, (SelectList)ViewBag.IngridientsList)
<br />
@Html.DropDownListFor(model => model.AmountID, (SelectList)ViewBag.AmountsList)
 <input type="submit" value="Create" />
}

2 个答案:

答案 0 :(得分:1)

您应该使用@Html.HiddenFor()帮助器。

在你的情况下:

@using(Html.BeginForm("AddIngridient","YourControllerName"))
{ 
   @Html.HiddenFor(x => x.IngredientID) //this line 
   @Html.DropDownListFor(model => model.IngredientTypeID, (SelectList)ViewBag.IngridientsList)
   <br />
   @Html.DropDownListFor(model => model.AmountID, (SelectList)ViewBag.AmountsList)
   <input type="submit" value="Create" />
}

它将生成input类型hidden,其名称为IngredientID,将在表单 POST 上传递给服务器。

答案 1 :(得分:1)

您应该更改AddIngredient Action的代码以返回模型:

public ActionResult AddIngridient(int id = 0)
{
    IEnumerable<Ingredient> ListOfIngridient =  FRE.Ingredient.Select(key => key).ToList();
    ViewBag.IngridientsList = new SelectList(ListOfIngridient,"IngredientID", "IngredientName");

    IEnumerable<Amount> ListOfAmounts = FRE.Amount.Select(key => key).ToList();
    ViewBag.AmountsList = new SelectList(ListOfAmounts, "AmountID", "AmountName");

    return View(new Ingredients { IngredientID = id });
}

在您的视图中添加隐藏的输入类型:

@using(Html.BeginForm())
{ 
   @Html.HiddenFor(model => model.IngredientID)
   @Html.DropDownListFor(model => model.IngredientTypeID, (SelectList)ViewBag.IngridientsList)
   <br />
   @Html.DropDownListFor(model => model.AmountID, (SelectList)ViewBag.AmountsList)
   <input type="submit" value="Create" />
}