How to set value in @Html.TextBoxFor in Razor syntax?
129,874
Solution 1
The problem is that you are using a lower case v.
You need to set it to Value and it should fix your issue:
@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })
Solution 2
I tried replacing value
with Value
and it worked out. It has set the value
in input
tag now.
@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })
Solution 3
It is going to write the value of your property model.Destination
This is by design. You'll want to populate your Destination property with the value you want in your controller before returning your view.
Solution 4
I tried replacing value
with Value
and it worked out. It has set the value
in input
tag now.
Solution 5
This works for me, in MVC5:
@Html.TextBoxFor(m => m.Name, new { @class = "form-control", id = "theID" , @Value="test" })
Author by
viki
Updated on October 04, 2020Comments
-
viki over 3 years
I have created an text-box using Razor and trying to set
value
as follows.@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", value= "3" })
I have tried appending
value
with@
@Html.TextBoxFor(model=> model.Destination, new { id = "txtPlace", @value= "3" })
even though it renders html
input
tag with emptyvalue
<input id="txtPlace" name="Destination" type="text" value class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset ui-mini" >
What am doing wrong?
-
Romias over 11 yearsAlthough it will work, I think a more neat way is to initialize the Destination property of your model in the Controller.
-
ManirajSS almost 10 yearshow to set Value for @Html.TextBoxFor using $('#id').val("myvalue") .Any clue?
-
Giles Roberts about 9 yearsIt doesn't always. If your route object contains a Destination parameter then MVC will use this in preference to the Destination property in your Model. stackoverflow.com/questions/7251241/…
-
Darth Scitus almost 5 yearsThank you, that probably saved me hours and hours.
-
jstuardo almost 4 years@Romias it depends on the use case. For example, I have a model that is used for both an edit dialog and a search dialog. In the edit dialog, it is OK. Default values are initialized properly and even
int
properties appear initialized with0
. However, for the search dialog, I need all the fields to be initially empty for obvious reasons. That is why the use of setting the value in the razor view makes sense. I don't know the real use case of the original question, though.