【发布时间】:2021-11-21 16:06:42
【问题描述】:
我有一个代码,我尝试将模型中的数据绑定到 DropDownListFor,它在执行时成功地在视图中显示下拉列表,但除了 0 之外,它始终不返回所选值。我已经检查并尝试了这里发布的许多解决方案,但似乎没有成功。
AdminController.cs(Create.cshtml 视图的 Create() 操作和 ProductSave() 表单操作)
public ActionResult Create()
{
var categoryList = _context.Categories.ToList();
var viewModel = new CreateViewModel
{
Categories = categoryList,
};
return View(viewModel);
}
[HttpPost]
public ActionResult ProductSave(CreateViewModel viewModel)
{
return Content(viewModel.SelectedId.ToString());
}
CreateViewModel.cs
public class CreateViewModel
{
public IEnumerable<Category> Categories { get; set; }
public int SelectedId { get; set; }
public Product Product { get; set; }
}
Create.cshtml(我这里只包含了视图的必要字段)
@using (Html.BeginForm("ProductSave", "Admin",null,FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="default-form-wrap style-2">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Product.Category_Id, new { @class = "control-label"})
<div class="nice-select single-select">
@Html.DropDownListFor(model => model.SelectedId,new SelectList(Model.Categories,"Id","CategoryName"),"Select Category", new { @class = "form-control" } )
@Html.ValidationMessageFor(model => model.Product.Category_Id, "", new { @class = "text-danger" })
</div>
</div>
<div class="row text-center">
<div class="col">
<input type="submit" value="Create" class="btn btn-base" />
</div>
</div>
</div>
选择类别后,值会相应更改 Screenshot
点击提交按钮后,我尝试在表单操作方法中返回 Content() 以查看绑定视图模型的输出
return Content(viewModel.SelectedId.ToString());
但这就是我得到的 Screenshot
我只想得到与所选列表项对应的输出。
【问题讨论】:
-
在您粘贴到此处的屏幕截图中,我没有看到 selectedId 作为控件名称。您可以尝试几件事:(1)手动将名称属性设置为下拉列表的“selectedId”。 (2)将selectedId的数据类型改为nullable int。
标签: c# asp.net .net entity-framework model-view-controller