我有一个用 Razor 编写的下拉列表,用于我正在开发的 MVC 应用程序:
@Html.DropDownList("BillId", "")
但是,用户不必根据我的程序逻辑选择任何内容(列表中填充了我的控制器中的“Bill”对象)。如果他们没有选择任何东西,我会收到错误
The ViewData item that has the key 'BillId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
如果未选择任何内容,如何在 Razor 中编写语句以返回 0 的 BillId?
我不确定语法,因为我有纯 Java 和 VB 的背景,但有些类似
If DropdownBox.SelectedIndex = 0
Else
BillId = DropdownBox.SelectedIndex
End
控制器如下:
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.BillIdList = New SelectList(BillList, "BillId", "BillDate")
ViewBag.BillId = New SelectList(BillList, "BillId", "BillDate")
Return View(job)
End Function
create 的 POST 函数如下:
<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
编辑
我也想知道这是如何传回的,因为在 POST 中我可以检查“null”?但是我觉得问题可能出在按下提交按钮的那一刻