我如何使用实体框架6数据库优先方法绑定DropDownList

问题描述 投票:0回答:1

[当我尝试用我的DropDownList加载页面时,出现错误“

    The model item passed into the dictionary is of type 'System.Web.Mvc.SelectList', but this dictionary requires a model item of type 'FBChecklist.Server'

在自动生成的模型(Server.cs)中,我手动添加了SelectListItem,如下所示:

    public partial class Application
{       
    public int ServerId { get; set; }
    public string ServerIp { get; set; }
    public Nullable<int> ApplicationId { get; set; }
    **public IEnumerable<SelectListItem> Applications** { get; set; }
}

这是我在SqlServer中的默认表结构:服务器表int ServerIdnvarchar(50)ServerIpint ApplicationId

并且DropDownList从申请表int ApplicationIdnvarchar(50)ApplicationName

和生成的模型:

    public partial class Application
   {
   public int ApplicationId { get; set; }
   public string ApplicationName { get; set; }
   }

在资源库(ServersService.cs)中,我正在按以下方式检索数据:

    public IEnumerable<SelectListItem> GetApplications()
    {
        using (var db = new AppEntities())
        {
            List<SelectListItem> applications = db.Applications.AsNoTracking()
                .OrderBy(n => n.ApplicationName)
                    .Select(n =>
                    new SelectListItem
                    {
                        Value = n.ApplicationId.ToString(),
                        Text = n.ApplicationName
                    }).ToList();
            var apptip = new SelectListItem()
            {
                Value = null,
                Text = "--- select application ---"
            };
            applications.Insert(0, apptip);
            return new SelectList(applications, "Value", "Text");
        }
    }

然后在控制器中,我已连接为:

    // GET: Servers/Create
   public ActionResult Create()
   {
       var apps = serversService.GetApplications();
       return View(apps);
   }


   [HttpPost]
   [ValidateAntiForgeryToken]
   public ActionResult Create([Bind(Include = "ServerIp,ServerName,ApplicationId")] Server server)
   {
       if (ModelState.IsValid)
       {
           serversService.AddServer(server); ;

           return RedirectToAction("Index");
       }

       return View(server);
   }

目前从我的研究看来,没有直接方法可以将诸如SelectListItem之类的属性添加到Database First中的自动生成的模型中。关于如何使用Database First方法或至少重构我实现代码的方式的任何帮助。我所看到的唯一可以添加到此局部类中的是数据注释。

对于上下文,这是我的观点:

                                             <div class="form-group">
                                                            <label class="col-sm-3 control-label no-padding-right" for="form-field-facebook">Application</label>

                                                            <div class="col-sm-9">
                                                                <span class="input-icon">
                                                                    @Html.DropDownListFor(x => Model.ApplicationId, new SelectList(Model.Applications, "Value", "Text"), htmlAttributes: new { @class = "form-control", id = "Country" })
                                                                    @Html.ValidationMessageFor(x => x.ApplicationId, "", new { @class = "text-danger" })
                                                                </span>
                                                            </div>
                                                        </div>
entity-framework razor binding dropdownlistfor
1个回答
0
投票

如果要添加仅对于视图存在的属性,则使用视图模型:

public class ServerViewModel
{
public ServerViewModel(Server server)
{
    ServerId = server.ServerId;
    ServerIp = server.ServerIp;
    ApplicationId = server.ApplicationId;
}

public ServerViewModel()
{
}

public int ServerId { get; set; }
public string ServerIp { get; set; }
public int? ApplicationId { get; set; }
public IEnumerable<SelectListItem> Applications { get; internal set; }

public void UpdateModel(Server server)
{
    server.ServerIp = ServerIp;
    server.ApplicationId = ApplicationId;
}

}

并且在视图中,我也传递了视图模型,而不是我的数据库优先模型:

@model ServerViewModel

Controller:

private void PopulateLookups(ServerViewModel model)
    {
    model.Applications = serversService.GetApplications();
    }

[HttpGet]
public ActionResult Create()
{
var model = new ServerViewModel();
PopulateLookups(model);
return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ServerViewModel model)
{
if (!ModelState.IsValid)
{
    PopulateLookups(model);
    return View(model);
}

var server = new Server();
model.UpdateModel(server);
serversService.AddServer(server);

return RedirectToAction("Index");
}
© www.soinside.com 2019 - 2024. All rights reserved.