Yosoyke Yosoyke - 1 year ago 182
Vb.net Question

How to add extra text to a TextBoxFor in MVC

I'm making a MVC form with all kind of fields. These are all in the normal MVC form

@Html.TextBoxFor(Function(x) x.Auto.Length, New With {.Class = "form-control", .Disabled = True})

Here I want to add the unit of measure in this field directly, in this case 'mm'.
I've already created an Extension which I'd like to call directly, but without success.

Public Function Add_Appendix(value As Integer, appendix As String) As String

Return value.ToString & " " & appendix
End Function

Would be nice if I could call it like:

@Html.TextBoxFor(Function(x) x.Auto.Length.Add_Appendix("mm"), New With {.Class = "form-control", .Disabled = True})

But then I'm getting the error

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

How can I make this possible?

Answer Source

The *For helpers do not allow random expressions because they need to bind to an existing property of your model. If you want to use a *For helper, you need to create a property on your model that represents the amended value.

If you don't want to do that, you have to use the helpers without *For (or not use any helpers at all), e.g. @Html.TextBox in your case.

Arguably though you should not be doing this because it only makes your life harder. You will have to make sure you strip the added mm when you post your model, and to make sure it does not add mm a second time. Instead put mm after the textbox.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download