我正在尝试将我的 dropdownlist
菜单中的所选项目保存到 MSSQL 表中,该菜单是从另一个 MSSQL 表填充的。但是每当我运行我的项目时,我都会遇到编译错误,
CS1502: The best overloaded method match for 'System.Web.Mvc.SelectList.SelectList(System.Collections.IEnumerable, string, string)' has some invalid arguments
这是我的代码,
查看
@using (Html.BeginForm("BoxManager", "Home"))
{
@Html.ValidationSummary(true)
<div class="editor-label">
<strong>Full Name</strong>
</div>
<div class="editor-field">
@Html.DropDownListFor(a => a.Boxes.clientname, new SelectList(Model.Clients, "fullname", "fullname"))
@Html.ValidationMessageFor(a => a.Boxes.clientname)
</div>
<p><input type="submit" class="btn btn-info" value="Add" /></p>
}
型号
public class BoxManagement
{
public BoxInfo Boxes { get; set; }
public IEnumerable<BoxInfo> BoxCollection { get; set; }
public ClientInfo Clients { get; set; }
}
Controller
public ActionResult BoxManager()
{
return View();
}
[HttpPost]
public ActionResult BoxManager(BoxManagement BoxModel)
{
if (ModelState.IsValid)
{
var AddBox = BoxModel.Boxes;
db.BoxInfoes.Add(AddBox);
db.SaveChanges();
return RedirectToAction("BoxPanel");
}
return View(BoxModel.Boxes);
}
我在这里做错了什么吗?如何在我的 BoxInfo
模型中保存下拉列表所选项目?非常需要这个帮助。交易。
最佳答案
原因是您正在传递 ClientInfo
类型的对象而不是所需的类型 IEnumerable<>
。您正在将以下行传递到下拉列表中:
new SelectList(Model.Clients, "fullname", "fullname")
Clients
类型为ClientInfo
这不是 IEnumerable
。您需要将其更改为代表 IEnumerable
的内容类型。
一个例子是:
Model.BoxCollection
这是IEnumerable
根据您的型号。
更新:
这应该是您的模型代码:
public class BoxManagement
{
public BoxInfo Boxes { get; set; }
public IEnumerable<BoxInfo> BoxCollection { get; set; }
public IEnumerable<ClientInfo> Clients { get; set; }
}
这应该是您的 Controller 代码:
var ClientCollection = db.ClientsInfo.Select(..conditions..).ToList();
Model.Clients = ClientCollection;
return View(Model);
所以基本上,只需绑定(bind) Clients
对象与您的查询 IEnumerable
并将该模型传递给您的 View 。这就是所需要的全部。
关于c# - 在 asp.net mvc 中保存下拉列表中的选定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30161719/