开发者

@Html.TextBoxFor for repeated properties in the model

Please help me solve this problem. I am currently trying to do this in MVC3, VB.NET.

Consider the following model:

Public Class SampleData
    Public Property PTY_1 as String
    Public Property PTY_2 as String
    Public Property PTY_3 as String
    '...开发者_开发百科snipped
    Public Property PTY_19 as String
    Public Property PTY_20 as String
End Class

Currently in my view, I have the following code:

<tr><td>@Html.TextBoxFor(Function(model) model.PTY_1)</td></tr>
<tr><td>@Html.TextBoxFor(Function(model) model.PTY_2)</td></tr>
<tr><td>@Html.TextBoxFor(Function(model) model.PTY_3)</td></tr>
'...snipped
<tr><td>@Html.TextBoxFor(Function(model) model.PTY_19)</td></tr>
<tr><td>@Html.TextBoxFor(Function(model) model.PTY_20)</td></tr>

As you can see, this will require 20 lines of code in my view. Is there a way to use a for-loop instead so that my view has fewer lines? Thanks.


Update 1. I have tried adding a new property PTY to my model to access the properties based on an index. Thus PTY(2) = PTY_2.

Public Class SampleData
    Public Property PTY(index as Integer) as String
        Get
            Select Case index
                Case 1 : Return PTY_1
                Case 2 : Return PTY_2
                Case 3 : Return PTY_3
                '...snipped
                Case 19 : Return PTY_19
                Case 20 : Return PTY_20
                Case Else : Return ""
            End Select
        End Get
        Set (value as String)
            Select case index
                Case 1 : PTY_1 = value
                Case 2 : PTY_2 = value
                Case 3 : PTY_3 = value
                '...snipped
                Case 19 : PTY_19 = value
                Case 20 : PTY_20 = value
            End Select
        End Set
    End Property
End Class

And as for the view, I have tried the following code:

@For index as Integer = 1 to 20
    <tr><td>@Html.TextBoxFor(Function(model) model.PTY(index))</td></tr>
End For

However when I load the view, I am getting an InvalidOperationException: "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions." T_T


You could decorate your properties with the [DataType(DataType.MultilineText)] attribute and in your view:

@Html.EditorForModel()

and if you want you could customize the template by using the [UIHint] attribute:

<DataType(DataType.MultilineText)> _
<UIHint("CustomTextArea")> _
Public Property PTY_1 as String

...

and then define an editor template (~/Views/Shared/EditorTemplates/CustomTextArea.cshtml):

<tr><td>@Html.TextArea("")</td></tr>


The matter is PTY_1 to PTY_20 is the names of your future inputs.
I write in C# :)

@for (int i = 1; i <= 20; i++)
{
    string name = "PTY_" + i;
    <tr><td><input type="text" name="@name" /></td></tr>
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜