我在mvc vb.net中绑定输入类型单选按钮时遇到问题。我在模型属性中传递值,但无法基于值绑定单选按钮。下面是单选按钮的html:
Checking:<input type="radio" id="rdChecking" name="C" value="Checking"/>
Savings:<input type="radio" id="rdSavings" name="S" value="Savings" />
在这里我定义了模型:
Public Class AgencySweepSettingsModel
....
....
Public Property AccountTypeChecking As String
Public Property AccountTypeSaving As String
End Class
这里我要在模型属性中传递值:
If dsAgencySweepInfo.Tables(0).Rows(0).Item(5) = "C" Then
.AccountTypeChecking = "C"
Else
.AccountTypeSaving = "S"
End If
请告诉我如何绑定此单选按钮。
答案 0 :(得分:1)
最好使用强类型的@Html.RadioButtonFor()
助手来解决单选按钮绑定问题,如下例所示:
模型
Public Class AgencySweepSettingsModel
' other properties
Public Property AccountType As String
End Class
查看
@Html.RadioButtonFor(Function (model) model.AccountType, "Checking", New With { Key .id = "rdChecking" })<label for="rdChecking">Checking</label>
@Html.RadioButtonFor(Function (model) model.AccountType, "Savings", New With { Key .id = "rdSavings" })<label for="rdSavings">Savings</label>
控制器操作
Public Function ActionName() As ActionResult
Dim model As AgencySweepSettingsModel = New AgencySweepSettingsModel()
' other stuff
' assume dsAgencySweepInfo is a DataSet
If dsAgencySweepInfo.Tables(0).Rows(0).Item(5) = "C" Then
model.AccountType = "Checking"
Else
model.AccountType = "Savings"
End If
' other stuff
Return View(model)
End Function
<HttpPost()>
Public Function ActionName(ByVal model As AgencySweepSettingsModel) As ActionResult
' do something
Return View(model)
End Function
如果您仍然想使用标准的BindAttribute
而不是强类型的视图模型,则name
元素的<input>
属性必须与包含属性名称的Include
部分匹配对于两个单选按钮:
<input type="radio" id="rdChecking" name="AccountType" value="Checking"/><label for="rdChecking">Checking</label>
<input type="radio" id="rdSavings" name="AccountType" value="Savings" /><label for="rdSavings">Savings</label>
请注意,由于单选按钮在同一组中始终只有一个选定值,因此应使用绑定到多个<input type="radio" />
元素的单个属性。