asp.net-mvc 如何设置默认值 HTML.TextBoxFor()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16625460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to set default value HTML.TextBoxFor()
提问by Fadi Alkadi
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>
}
回答by MotoSV
Create an instance of the model in your action, assign some values to the properties of the model and pass that into the Viewmethod.
在您的操作中创建模型的实例,为模型的属性分配一些值并将其传递到View方法中。
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.
这会将模型传递给视图并TextBoxFor( model => model.Position )显示5.
回答by Nazar Iaremii
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
它在 MVC 4 上的工作
Hope Its will be usefull info for another people.
希望它对其他人有用。

