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" })
Share:
129,874
viki
Author by

viki

Updated on October 04, 2020

Comments

  • viki
    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 empty value

    <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
    Romias over 11 years
    Although it will work, I think a more neat way is to initialize the Destination property of your model in the Controller.
  • ManirajSS
    ManirajSS almost 10 years
    how to set Value for @Html.TextBoxFor using $('#id').val("myvalue") .Any clue?
  • Giles Roberts
    Giles Roberts about 9 years
    It 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
    Darth Scitus almost 5 years
    Thank you, that probably saved me hours and hours.
  • jstuardo
    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 with 0. 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.