如何将模型数据获取到视图下拉列表

时间:2019-04-17 19:43:55

标签: c# asp.net asp.net-mvc

尝试使用模型中的数据填充下拉列表字段。运行代码时,出现错误消息: VS2017输出屏幕中的“抛出异常:System.Web.Mvc.dll中的'System.InvalidOperationException'。”

模型:

namespace FulfillmentPortal.Models
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Collections.Generic;

public partial class Carrier
{
    public int CarrierId { get; set; }

    [StringLength(50)]
    public string CarrierName { get; set; }
}

public partial class CarrierModel : DbContext
{
    public CarrierModel()
        : base("name=CarrierModel")
    {
    }

    public virtual DbSet<Carrier> Carriers { get; set; }

    public virtual DbSet<CarrierService> CarrierServices { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    }
}
}

控制器:

namespace FulfillmentPortal.Controllers
{
public class FulfillmentController : Controller
{
    private CarrierModel db = new CarrierModel();

    // GET: Fulfillment
    public ActionResult Index()
    {
        var carrierList = db.Carriers.ToList();
        return View(carrierList);
    }  
}
}

视图:

@model FulfillmentPortal.Models.Carrier
@{
    ViewBag.Title = "index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="panel panel-primary">
<div class="panel-heading">REPORT OPTIONS</div>
<div class="panel-body">
<form id="processForm" class="form-horizontal" action="~/Fulfillment/Report" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="sel1">Carrier:</label>
        @Html.DropDownListFor(m => m.Carriers, new SelectList(Model.Carriers, "CarrierId", "CarrierName"), " ");       
        <label for="sel2">Carrier Services:</label>
        <select class="form-control" id="sel2" style="width: auto; margin-bottom:15px;">
            <option value="-1" selected>Select One</option>
        </select>
    </div>
</form>
</div>
</div>

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

问题是您要向视图传递载体对象列表

var carrierList = db.Carriers.ToList();
return View(carrierList);

但是您的视图接受单个运营商对象

@model FulfillmentPortal.Models.Carrier

如果要遵循MVC模式:

您应该创建一个新的Viewmodel对象,其中包含Carrier对象的列表,然后将其传递给视图。

class ViewModel {
   public List<Carrier> carrierList {get; set;}
}

在您的控制器中:

public ActionResult Index()
{
    ViewModel vm = new ViewModel();
    vm.carrierlist = db.Carriers.ToList();
    return View(vm);
}  

然后,您的视图应接受一个ViewModel对象:

@model ViewModel

如果您不想遵循MVC模式:

更改视图以接受运营商对象列表

@model List<FulfillmentPortal.Models.Carrier>