@Html.DropDownList在提交时返回null
本文关键字:返回 null 提交 DropDownList @Html | 更新日期: 2023-09-27 18:10:57
这里有一个场景。我想在表单中创建一个HTTP POST
动作,我是这样做的。
public class Item
{
public Item()
{
Storages = new HashSet<Storage>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Storage> Storages { get; set; }
-- remove some lines for brevity --
}
public class Storage
{
public int Id { get; set; }
public string Name { get; set; }
--- remove some lines for brevity --
}
所以基本上,一个Item
有许多Storage
所以我创建了viewmodel
public class CreateStockViewModel
{
public string Name { get; set; }
public int StorageId { get; set; }
-- remove some lines for brevity --
}
在我的Controller
。我有这个
[HttpGet]
public ActionResult Create()
{
ViewBag.Storages = _storageService.All
.OrderBy(i => i.Name)
.ToSelectList(s => s.Name, s => s.Id);
return View();
}
In my View
@model Wsfis.Web.ViewModels.ItemViewModels.CreateStockViewModel
@Html.DropDownList("Storages")
现在我的问题是,当我提交表单。并有Quick Watch
模型被传递。Null
或0
public ActionResult Create(CreateStockViewModel item)
{
// some code
}
简而言之,
- 当我提交表单时,除了
@Html.DropDownList
之外,所有字段都被绑定。我错过了什么?
附加说明:
- 他们说
Views
应该是强类型的。那么我应该在View
传递什么呢?(一个示例代码将是伟大的。谢谢)对于ToSelectList
方法,我复制此代码(我希望它是正确的)
任何帮助都将非常感激。谢谢。
您的表单输入与您的属性有不同的名称,因此默认的模型绑定器不知道如何绑定您的模型。
您可以传入一个不同的名称来使用DropDownList帮助器,但是我更喜欢使用强类型的帮助器:
@Html.DropDownListFor(m => m.StorageId, ViewBag.Storages as IEnumerable<SelectListItem>)
试试:
ViewBag.StorageId = _storageService.All
.OrderBy(i => i.Name)
.ToSelectList(s => s.Name, s => s.Id);
在视图:@Html.DropDownList("StorageId")
它现在将发布下拉列表选择值在CreateStockViewModel
对象的StorageId
属性。