3

我有一个由表单和文本框组成的视图。如何在每个框中为字符串和 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>


}
4

2 回答 2

8

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

在你的行动中有:

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

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

于 2013-05-18T14:42:13.720 回答
7

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

在控制器中

 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})

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

它在 MVC 4 上的工作

希望它对其他人有用。

于 2013-12-28T15:08:03.363 回答