Html.EditorFor Set Default Value
Better option is to do this in your view model like
public class MyVM
{
int _propertyValue = 5;//set Default Value here
public int PropertyName{
get
{
return _propertyValue;
}
set
{
_propertyValue = value;
}
}
}
Then in your view
@Html.EditorFor(c => c.PropertyName)
will work the way u want it (if no value default value will be there)
Here's what I've found:
@Html.TextBoxFor(c => c.Propertyname, new { @Value = "5" })
works with a capital V, not a lower case v (the assumption being value is a keyword used in setters typically) Lower vs upper value
@Html.EditorFor(c => c.Propertyname, new { @Value = "5" })
does not work
Your code ends up looking like this though
<input Value="5" id="Propertyname" name="Propertyname" type="text" value="" />
Value vs. value. Not sure I'd be too fond of that.
Why not just check in the controller action if the proprety has a value or not and if it doesn't just set it there in your view model to your defaulted value and let it bind so as to avoid all this monkey work in the view?
Its not right to set default value in View. The View should perform display work, not more. This action breaks ideology of MVC pattern. So the right place to set defaults - create method of controller class.
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" })