1

我正在尝试使用以下下拉框来选择要为模型编辑的值范围。

到目前为止,我已经得到了以下代码:

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

但本质上我想在这里保存该字符串而不是这个:

@Html.EditorFor(Function(model) model.ServiceName)

我的看法是:

@Using Html.BeginForm()
    @Html.ValidationSummary(True)
    @<fieldset>
        <legend>RequestedService</legend>

        <div class="editor-label">
            @Html.LabelFor(Function(model) model.ServiceId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(Function(model) model.ServiceId)
            @Html.DropDownList("Services", "")
            @Html.ValidationMessageFor(Function(model) model.ServiceId)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
End Using

目前这两件事。

我的控制器:

Function AddService(id As Integer) As ViewResult
        Dim serv As RequestedService = New RequestedService
        serv.JobId = id

        Dim ServiceList = New List(Of String)()

        Dim ServiceQuery = From s In db.Services
                           Select s.ServiceName

        ServiceList.AddRange(ServiceQuery)

        ViewBag.Services = New SelectList(ServiceList)

        Return View(serv)
    End Function

最后是我的模型:

Imports System.Data.Entity
Imports System.ComponentModel.DataAnnotations

Public Class RequestedService

Public Property RequestedServiceId() As Integer


Public Property ServiceId() As Integer

<Required()>
<Display(Name:="Job Number *")>
Public Property JobId() As Integer

<Required()>
<Display(Name:="Station ID *")>
Public Property StationId() As Integer

End Class
4

1 回答 1

1

SelectList您需要告诉选择列表的问题是值和显示文本是什么。您不能只传递字符串列表,以正确填充,添加键和值,如下所示

Dim ServiceQuery = (From s In db.Services
                       Select s)

可能是这样如果您需要与服务相关的ID

ViewBag.Services = New SelectList(ServiceList, s.IDServices, s.ServiceName)

或者像这样如果您需要值的唯一文本

ViewBag.Services = New SelectList(ServiceList, s.ServiceName, s.ServiceName)

更新

要完成此操作,您需要修改视图和您的操作。

首先在您的操作中更改您的 Viewbag 元素的名称,如下所示

ViewBag.ServiceId = New SelectList(ServiceList, s.IDServices, s.ServiceName)

现在你的观点明显的变化是

@Using Html.BeginForm()
@Html.ValidationSummary(True)
@<fieldset>
    <legend>RequestedService</legend>

    <div class="editor-label">
        @Html.LabelFor(Function(model) model.ServiceId)
    </div>
    <div class="editor-field">
        @Html.DropDownList("ServiceId", "")
        @Html.ValidationMessageFor(Function(model) model.ServiceId)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

结束使用

所以你不需要

@Html.EditorFor(Function(model) model.ServiceId)

当用户从下拉列表中选择选项并单击创建按钮时,属性 ServiceID 将自动映射到您的类中,即 mvc3 与元素的名称一起为您完成所有神奇的工作

于 2012-08-13T19:00:11.340 回答