繁体   English   中英

从asp.net MVC中的下拉列表中保存所选项目

[英]Save selected item from dropdownlist in asp.net mvc

我试图将我的dropdownlist菜单中的选定项目保存在MSSQL表中,该菜单是从另一个MSSQL表中填充的。 但是每当我运行项目时,我都会得到编译错误,

CS1502:“ System.Web.Mvc.SelectList.SelectList(System.Collections.IEnumerable,字符串,字符串)”的最佳重载方法匹配具有一些无效的参数

这是我的代码,

视图

@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; }
}

调节器

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模型中保存下拉列表选择的项目? 急需此帮助。 TNX。

原因是您传递的是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; }
}

这应该是您的控制器代码:

var ClientCollection = db.ClientsInfo.Select(..conditions..).ToList();
Model.Clients = ClientCollection;
return View(Model);

因此,基本上,只需将带有查询的Clients对象绑定到IEnumerable然后将该模型传递给您的视图。 这就是所需要的。

您在SelectList声明中使用了错误的字段,在使用Client ,但是不应该将其作为Boxes因为那是项目列表。 SelectList构造函数中的第一项必须是IEnumerable

如果您的意思是方框,请尝试:

@Html.DropDownListFor(a => a.Boxes.clientname, new SelectList(Model.BoxCollection, "fullname", "fullname"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM