gpt4 book ai didi

asp.net-mvc-3 - asp.net mvc 3 Dropdownlist问题,必须是类型 'IEnumerable'?

转载 作者:行者123 更新时间:2023-12-03 06:57:47 25 4
gpt4 key购买 nike

当我点击保存时出现以下错误:

具有“SelectedCategoryId”键的 ViewData 项的类型为“System.Int32”,但必须为“IEnumerable”类型?

我的 Controller :

public ActionResult IndexTwee()
{

var listCategories = new List<SelectListItem>();

listCategories.Add(new SelectListItem() {Text="foo",Value="1" });
listCategories.Add(new SelectListItem() { Text = "bar", Value = "2" });

MyViewModelTwee model = new MyViewModelTwee() { };

model.Categories = listCategories;
model.SelectedCategoryId = 2;

return View(model);
}


[HttpPost]
public ActionResult IndexTwee(MyViewModelTwee Model)
{

return View(Model);

}

我的模型:

  public class MyViewModelTwee
{
public int SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}

我的观点:

@model mvc3DropDown.Models.MyViewModelTwee
@using (Html.BeginForm())
{
@Html.DropDownListFor(
x => x.SelectedCategoryId,
Model.Categories
)
<button>Save</button>

}

最佳答案

不要忘记在 POST 操作中重新绑定(bind)列表:

[HttpPost]
public ActionResult Index(MyViewModelTwee Model)
{
var listCategories = new List<SelectListItem>();
listCategories.Add(new SelectListItem() { Text = "foo", Value = "1" });
listCategories.Add(new SelectListItem() { Text = "bar", Value = "2" });
Model.Categories = listCategories;
return View(Model);
}

请记住,当您提交 html <form> 时,仅发送所选值。其他值会丢失,因此您需要从 GET 操作中获取它们的位置重新获取它们。当然,您将将此代码外部化到存储库层中,以便您的代码现在如下所示:

public ActionResult IndexTwee()
{
var model = new MyViewModelTwee
{
SelectedCategoryId = 2,
Categories = _repository.GetCategories()
};
return View(model);
}

[HttpPost]
public ActionResult IndexTwee(MyViewModelTwee Model)
{
Model.Categories = _repository.GetCategories();
return View(Model);
}

关于asp.net-mvc-3 - asp.net mvc 3 Dropdownlist问题,必须是类型 'IEnumerable<SelectListItem>'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7461128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com