asp.net-mvcasp.net-mvc-3formshtml.textboxfor

how to set default value HTML.TextBoxFor()


I have a view consisting of a form and textboxes. How can I set a default value in each box for strings and int values?

I want the page to load up each box's value so I don't need to type values.

I'm not able to change anything in the Model.

@model MyDb.Production.ProductionMaterial

@{
  ViewBag.Title = "CreateMaterial";
 }


@using (Html.BeginForm()) {
  @Html.ValidationSummary(true)
  <fieldset>
    <legend>ProductionOrderMaterial</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Position)
    </div>
    <div class="editor-field">                   //something like
        @Html.TextBoxFor(model => model.Position, Or 5 )
        @Html.ValidationMessageFor(model => model.Position)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.ArticleId)
    </div>
    <div class="editor-field">                  //something like
        @Html.TextBoxFor(model => model.ArticleId. Or "")
        @Html.ValidationMessageFor(model => model.ArticleId)
    </div>


}

Solution

  • Create an instance of the model in your action, assign some values to the properties of the model and pass that into the View method.

    In your action have:

    ProductionMaterial model = new ProductionMaterial();
    model.Position = 5;
    return this.View(model);
    

    This will pass the model to the view and TextBoxFor( model => model.Position ) will display 5.