Html.EditorFor Set Default Value

后端 未结 12 1840
夕颜
夕颜 2020-12-13 03:44

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

相关标签:
12条回答
  • 2020-12-13 03:46

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

    [DefaultValue(false)]
    public bool TestAccount { get; set; }
    
    0 讨论(0)
  • 2020-12-13 03:46

    This worked for me

    In Controlle

     ViewBag.AAA = default_Value ;
    

    In View

    @Html.EditorFor(model => model.AAA, new { htmlAttributes = new { @Value = ViewBag.AAA } }
    
    0 讨论(0)
  • 2020-12-13 03:50

    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?

    0 讨论(0)
  • 2020-12-13 03:53

    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.

    0 讨论(0)
  • 2020-12-13 03:56

    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)

    0 讨论(0)
  • 2020-12-13 03:57

    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);
        }
    
    0 讨论(0)
提交回复
热议问题