Rookie question. I have a parameter being passed to a create view. I need to set a field name with a default value. @Html.EditorFor(model => model.Id) I need to set this in
This is my working code:
@Html.EditorFor(model => model.PropertyName, new { htmlAttributes = new { @class = "form-control", @Value = "123" } })
my difference with other answers is using Value inside the htmlAttributes array
I just did this (Shadi's first answer) and it works a treat:
public ActionResult Create()
{
Article article = new Article();
article.Active = true;
article.DatePublished = DateTime.Now;
ViewData.Model = article;
return View();
}
I could put the default values in my model like a propper MVC addict: (I'm using Entity Framework)
public partial class Article
{
public Article()
{
Active = true;
DatePublished = Datetime.Now;
}
}
public ActionResult Create()
{
Article article = new Article();
ViewData.Model = article;
return View();
}
Can anyone see any downsides to this?
Shove it in the ViewBag
:
Controller:
ViewBag.ProductId = 1;
View:
@Html.TextBoxFor(c => c.Propertyname, new {@Value = ViewBag.ProductId})
For me I need to set current date and time as default value this solved my issue in View add this code :
<div class="form-group">
@Html.LabelFor(model => model.order_date, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.order_date, new { htmlAttributes = new { @class = "form-control",@Value= DateTime.Now } })
@Html.ValidationMessageFor(model => model.order_date, "", new { @class = "text-danger" })
</div>
</div>
The clean way to do so is to pass a new instance of the created entity through the controller:
//GET
public ActionResult CreateNewMyEntity(string default_value)
{
MyEntity newMyEntity = new MyEntity();
newMyEntity._propertyValue = default_value;
return View(newMyEntity);
}
If you want to pass the default value through ActionLink
@Html.ActionLink("Create New", "CreateNewMyEntity", new { default_value = "5" })
This worked for me:
In the controller
*ViewBag.DefaultValue= "Default Value";*
In the View
*@Html.EditorFor(model => model.PropertyName, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter a Value", @Value = ViewBag.DefaultValue} })*