我可以在下拉列表中显示数据库中的值以及需要值的位置。但是在创建内容时,我无法从下拉列表中获取值到我的数据库。它变得空了。我尝试过s.o.f的一些解决方案,但它们没有用。
型号1:
public class Kategori
{
[Key]
public int KategoriID { get; set; }
public string Namn { get; set; }
}
型号2:
public class Inlägg
{
[Key]
public int InläggsID { get; set; }
public Kategori Kategori { get; set; }
}
控制器:
// POST: Inlägg/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Titel,Text,Kategori.Namn")] Inlägg inlägg)
//The Kategori is getting null
{
if (ModelState.IsValid)
{
inlägg.Datum = DateTime.Now;
_context.Add(inlägg);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(inlägg);
}
视图:
@Html.DropDownList("Kategori", null, htmlAttributes: new { @class = "form-control" })
我尝试过使用SelectItemList,选择选项值,在Models类中有一个SelectItem,也是Inlägg里面的“公共Kategori列表”。真的不知道如何解决这个问题。我今天刚试了8个小时,昨天又跑了2个小时。如何获取用户在下拉列表中选择的值而不是获取null?告诉我是否需要发送更多代码:-)
你应该改变它;
@Html.DropDownList("Kategori", null, htmlAttributes: new { @class = "form-control" })
至
@Html.DropDownList("SelectedCategory", ViewData["Kategori"] as SelectList, htmlAttributes: new { @class = "form-control" })
选定的下拉元素作为SelectedCategory
传递给serverside。另外,我强烈建议您使用Model
类而不是ViewData
来在控制器和视图之间传输数据。
您需要为外键值添加另一个属性。由于您的其他相关实体类名称是Kategori
,因此您可以将此新属性命名为KategoriId
,以使其与外键属性名称的约定相匹配。
public class Inlagg
{
[Key]
public int InläggsID { get; set; }
public string Titel { get; set; }
public string Text { get; set; }
public DateTime Datum { get; set; }
public virtual Kategori Kategori { get; set; }
public int? KategoriId { set;get;} // This is the new property
}
现在在视图中的表单中,确保DropDownList
帮助器呈现的select元素具有与新属性名称相同的name
属性值(检查页面的视图源)
@Html.DropDownList("KategoriId", ViewData["Kategori"] as SelectList)
最后,确保在Bind
属性Include
列表中包含这个新的输入名称/属性名称,以便模型绑定器绑定它。
public async Task<IActionResult> Create([Bind(Include="Titel,Text,KategoriId")]
Inlagg inlagg)
{
// to do : your code for saving and returning something
}
另一种选择是使用仅具有所需属性的视图模型,而不是将Bind
属性与实体类一起使用