82

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 input field with name Id with a default value that is being passed to the view via an actionlink.

So, how can this input field --@Html.EditorFor(model => model.Id) -- get set with a default value.

Would the following work?? Where the number 5 is a parameter I pass into the text field to set default value.

@Html.EditorFor(c => c.PropertyName, new { text = "5"; })
tereško
  • 58,060
  • 25
  • 98
  • 150
Nate
  • 2,044
  • 4
  • 23
  • 47

13 Answers13

109

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?

Community
  • 1
  • 1
Khepri
  • 9,547
  • 5
  • 45
  • 61
  • 4
    **NEVER** set the value attribute when using `HtmlHelper` methods. You set the value of the property in the GET method before you pass the model to the view. –  Dec 05 '17 at 11:30
  • and why is that? – Baksteen Dec 10 '20 at 15:58
69

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" })
Shadi
  • 2,236
  • 2
  • 22
  • 22
  • This is the solution I ended up using. Anton Semenov is correct: the ideology of MVC requires the developer to set default values in the Controller and not in the View. – Jake Dec 04 '12 at 16:26
18

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.

Eugene
  • 2,965
  • 2
  • 34
  • 39
Anton Semenov
  • 6,227
  • 5
  • 41
  • 69
16

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)

Mathias Lykkegaard Lorenzen
  • 15,031
  • 23
  • 100
  • 187
Muhammad Adeel Zahid
  • 17,474
  • 14
  • 90
  • 155
  • Why would I hard code a property value in the VM? That makes no sense to me, but maybe I'm trying to do something different? I'm trying to pass the query string parameter, id, to the Create view and populate the EditorFor helper with that id value, so it will save the FK id in the db. How do I do that? – Katherine Aug 08 '18 at 03:40
4

Shouldn't the @Html.EditorFor() make use of the Attributes you put in your model?

[DefaultValue(false)]
public bool TestAccount { get; set; }
Zapnologica
  • 22,170
  • 44
  • 158
  • 253
  • Good idea, but EditorFor ignored this Model attribute for me. However creating a constructor in the Model with the property set to desired default value worked for me. – Andrew Nov 07 '22 at 10:02
4

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?

Smithy
  • 2,170
  • 6
  • 29
  • 61
  • 1
    These are fixed default values, if you want to provide it durinng run time, you need different approach. – Shadi Jan 06 '12 at 16:16
  • 1
    Thanks @Shadi, technically Datetime.Now isn't a fixed value. If the default value *was* generated at runtime, would it be the models responsibility or the controller? – Smithy Jan 13 '12 at 18:08
  • 3
    Just refering to the MVC rules (you can break it!) Model is just for holding the data, View for viewing it, and your business should be placed into the Controller or classes accessed by the controller. Short answer, it's the controller responsibility. – Shadi Jan 17 '12 at 10:33
3

Shove it in the ViewBag:

Controller:

ViewBag.ProductId = 1;

View:

@Html.TextBoxFor(c => c.Propertyname, new {@Value = ViewBag.ProductId})
vapcguy
  • 7,097
  • 1
  • 56
  • 52
2

This worked for me

In Controlle

 ViewBag.AAA = default_Value ;

In View

@Html.EditorFor(model => model.AAA, new { htmlAttributes = new { @Value = ViewBag.AAA } }
Mohamed Wardan
  • 116
  • 2
  • 8
2

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>
Ziad Adnan
  • 710
  • 5
  • 18
1

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} })*
Joe
  • 349
  • 2
  • 3
0

In the constructor method of your model class set the default value whatever you want. Then in your first action create an instance of the model and pass it to your view.

    public ActionResult VolunteersAdd()
    {
        VolunteerModel model = new VolunteerModel(); //to set the default values
        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult VolunteersAdd(VolunteerModel model)
    {


        return View(model);
    }
Ozan BAYRAM
  • 2,780
  • 1
  • 28
  • 35
0

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

Hamed Rezaei
  • 370
  • 1
  • 3
  • 11
0

Instead of using controller or html helper.You can also use Jquery to set default value to model attribute.

   $('#PropertyName').val(15);