在视图中创建下拉列表并将值传递给控制器- MVC
本文关键字:控制器 MVC 值传 视图 创建 下拉列表 | 更新日期: 2023-09-27 18:09:29
如何在视图中创建值为1-10(int)的下拉列表并将所选值传递给控制器?
UserReview模型:
public System.Guid Id { get; set; }
public System.Guid UserId { get; set; }
public System.Guid ReviewId { get; set; }
public Nullable<int> Rating { get; set; }
控制器:
public ActionResult Rating(Guid id) //got its ReviewId from previous page
{
//so far empty, no clue what to do
return Content("");
}
1)第一个方法鉴于
<select name="YourDropDownValue">
@for(int i = 1 ; i <= 10 ; i++)
{
<option value="@i">@i</option>
}
</select>
尝试使用这段代码,在name属性中,你必须保留你想要传递给控制器的字段名
在控制器中这是你绑定下拉值
的方式 [HttpPost]
public ActionResult getDropDown(int YourDropDownValue)
{
}
2)第二种方法将其保存在控制器中get
List<int> Num = new List<int>() { 1,2,3,4,5,6,7,8,9,10 };
ViewBag.Number = new SelectList(Num);
现在在视图
@Html.DropDownListFor(x => x.YourDropDownValue, ViewBag.Number as SelectList)
如果没有模型
@Html.DropDownList("YourDropDownValue", ViewBag.Number as SelectList)
现在在控制器
[HttpPost]
public ActionResult getDropDown(int YourDropDownValue)
{
}