[c#] Html.EditorFor Set Default Value

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 [email protected](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"; })

This question is related to c# asp.net-mvc asp.net-mvc-3

The answer is


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

[DefaultValue(false)]
public bool TestAccount { get; set; }

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?


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.


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>

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?


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)


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


This worked for me

In Controlle

 ViewBag.AAA = default_Value ;

In View

@Html.EditorFor(model => model.AAA, new { htmlAttributes = new { @Value = ViewBag.AAA } }

Shove it in the ViewBag:

Controller:

ViewBag.ProductId = 1;

View:

@Html.TextBoxFor(c => c.Propertyname, new {@Value = ViewBag.ProductId})

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} })*

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);
    }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC