如何设置默认值HTML.TextBoxFor()

时间:2013-05-18 14:38:29

标签: asp.net-mvc asp.net-mvc-3 forms html.textboxfor

我有一个由表单和文本框组成的视图。 如何在字符串和int值的每个框中设置默认值?

我希望页面加载每个框的值,因此我不需要键入值。

我无法改变模型中的任何内容。

@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>


}

2 个答案:

答案 0 :(得分:8)

在您的操作中创建模型的实例,为模型的属性指定一些值并将其传递到View方法。

在你的行动中:

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

这会将模型传递给视图,TextBoxFor( model => model.Position )会显示5

答案 1 :(得分:6)

我看到你已经得到答案,但我会告诉你如何以另一种方式做到:

在控制器中

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


                return View();
            }

在视图中

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

当您加载View时,您将获得具有默认值的字段(在我们的示例中为当前日期)

它在MVC 4上的工作

希望它对另一个人有用。

相关问题