c# - 在 asp.net mvc 中保存下拉列表中的选定项目

标签 c# asp.net sql-server asp.net-mvc razor

我正在尝试将我的 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/

相关文章:

c# - 如何在 SELECT 查询中为 fieldName IN @fieldName 构造添加参数

c# - Signalr 客户端版本 1.5,服务器版本未定义

c# - CookieContainer 不存储国际化域名的 cookie

c# - Twilio 消息发送在 ASP .NET 中不起作用

c# - 如何使用 WebClient.DownloadData(到本地 DummyPage.aspx)

java - SQL 更新列从一个表到另一个

SQL Server XML-DML如何用相对xpath的值替换元素值

c# - 在C#中将Excel上传到SQL Server时自动添加上传者(用户名或名称)

c# - 使用哪种轻量级数据网格?

c# - 如何使用这些 cURL 命令调用访问 token 的 REST Web API - 在 C# 中