how to set default value HTML.TextBoxFor()
Solution 1
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
.
Solution 2
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.
Fadi Alkadi
Updated on July 09, 2022Comments
-
Fadi Alkadi almost 2 years
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> }