下拉列表的默认值

时间:2012-08-16 17:05:39

标签: vb.net asp.net-mvc-3

我需要为DropDown列表设置一个默认值,如下所示:

@Html.DropDownList("BillId", "") 

用户不一定需要选择某些内容,但列表会抛出错误

The ViewData item that has the key 'BillId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'

如果未选择某个值,则该框保留在其默认的空白状态。

我的控制器如下:

    Function Create(id As Integer) As ViewResult
        ViewBag.id = id
        Dim job As Job = New Job
        job.CustomerId = id
        job.JobAmount = 0
        job.JobDate = Date.Now()
        job.JobStatus = "Active"

        Dim BillList = New List(Of Bill)()

        Dim BillQuery = From s In db.Bills
                        Select s

        BillList.AddRange(BillQuery)

        ViewBag.BillId = New SelectList(BillList, "BillId", "BillDate")

        Return View(job)
    End Function

    '
    ' POST: /Job/Create

    <HttpPost()>
    Function Create(job As Job) As ActionResult
        If ModelState.IsValid Then
            db.Jobs.Add(job)
            db.SaveChanges()

            Dim customer As Customer = db.Customers.Find(job.CustomerId)
            Dim customerNumber As String = customer.CustCellphone.ToString()
            Dim messageSender As SendMessage = New SendMessage
            Dim smsMessage As String = "LAUNDRY: Job Number " & job.JobId & " has been booked in. You will be notified when individual services within it are ready for collection."
            messageSender.SendMessage(smsMessage, customerNumber)

            Dim url As String = "/RequestedService/AddService/" + job.JobId.ToString()
            Return Redirect(url)
        End If
        Return View(job)
    End Function

1 个答案:

答案 0 :(得分:0)

如果你的模型Job没有BillId的属性,那么下拉标记应该是

@Html.DropDownList("Job_BillId", ViewBag.BillId)

模型Job包含属性BillId,而不是创建具有不同名称的ViewBag,并在视图标记中相应地使用它们,例如:

在控制器

中创建一个不同名称而不是BillId的ViewBag
ViewBag.BillIdList =  New SelectList(BillList, "BillId", "BillDate")

在视图中使用如下

@Html.DropDownListFor(model => model.BillId, ViewBag.BillIdList)

希望这会对你有所帮助。