문제

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>


}
도움이 되었습니까?

해결책

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.

다른 팁

I see you already got answer, but I'll show you how you can do it another way:

In Controller

 public ActionResult Index()
            {
                //here you must set VALUE what u want,
                //for example I set current date
                Viewbag.ExactlyWhatYouNeed = DateTime.Now 


                return View();
            }

In View

  @Html.TextBoxFor(model => model.CurrentDate, new { @Value = ViewBag.ExactlyWhatYouNeed})

And when you will load your View, you will get field with default value (current date in our example)

Its work on MVC 4

Hope Its will be usefull info for another people.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top