user4864716
user4864716

Reputation:

How can I make my EditorFor disabled?

I have an MVC Razor Create view and my model contains one or more fields that need to be auto-filled by the system, such as "Timestamp" and "Username". Because these fields are required, they need to be in the form.

Here is an example of what the default code looks like when you allow Visual Studio to scaffold your views from a controller.

        <div class="form-group">
        @Html.LabelFor(model => model.RoseUserName, 
            htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.RoseUserName, 
                  new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.RoseUserName, "", 
                  new { @class = "text-danger" })
        </div>
    </div>

This what the code looks like when rendered. It's functional, but the first and third fields are fully editable when it shouldn't be. So the question is how we can have EditorFor fields that feed the correct data into the model when the form is submitted but that the user can't change?

This is what the default Create form looks like

Further Explanation While there are some reasons you might want to keep those fields hidden from view, there are also valid reasons you would want these fields to be seen by the user, such as in a company intranet with users who expect to see that information. While a datestamp could be autogenerated by SQL Server with a getdate() default value, capturing the user's identity under Windows Authentication would need to be done from from the MVC side. The identification of the user is part of the model.

Upvotes: 1

Views: 3668

Answers (3)

edward
edward

Reputation: 75

<div class="form-group">
    @Html.LabelFor(model => model.RoseUserName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.RoseUserName, new { htmlAttributes = new { @class = "form-control", disabled = "disabled", @readonly = "readonly"} })
        @Html.ValidationMessageFor(model => model.RoseUserName, "", new { @class = "text-danger" })
    </div>
</div>

Add disabled = "disabled", @readonly = "readonly" along with @class = "form-control", so you have:

@Html.EditorFor(model => model.RoseUserName, new { htmlAttributes = new { @class = "form-control", disabled = "disabled", @readonly = "readonly"} })

Upvotes: 0

user4864716
user4864716

Reputation:

When I posted this answer, it was based on what I was able to find so far. I have learned that this is a case of "Beware what you wish for." The other answers provided point out correctly that following the approach shown below is not a good practice and has at least one false premise, as explained in the conversation thread.

This is useful only as an explanation of what NOT to do. The answer I accepted shows the approach I adopted.

The answer is amazingly simple and elegant. Tt just takes an extra phrase: @readonly="readonly".

In better context, the original example was:

        <div class="form-group">
        @Html.LabelFor(model => model.RoseUserName, 
            htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.RoseUserName, 
                  new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.RoseUserName, "", 
                  new { @class = "text-danger" })
        </div>

All you do is add@readonly="readonly"to the EditorFor htmlAttributes, like this:

@Html.EditorFor(model => model.RoseUserName, 
     new { htmlAttributes = new { @class = "form-control", @readonly="readonly" } })

Problem solved.

This is the EditorFor with a <code>@readonly="readonly" added to the htmlAttributes</code>

Upvotes: 0

pool pro
pool pro

Reputation: 2104

An important database features is the ability to have computed properties. If you're mapping your code first classes to tables that contain computed properties, you don't want Entity Framework to try to update those columns. But you do want EF to return those values from the database after you've inserted or updated data. You can use the DatabaseGenerated annotation to flag those properties in your class along with the Computed enum. Other enums are None and Identity.

[DatabaseGenerated(DatabaseGenerationOption.Computed)] 
     public DateTime DateCreated { get; set; }

Now just have your database generate the time stamp when the record is created. You can also set DataAnnotation to read only like so

[DatabaseGenerated(DatabaseGenerationOption.Computed)] 
[Editable(false)]
public DateTime DateCreated { get; set; }

Hope this helps Update

// Private
private DateTime _createdOn = DateTime.Now;
// Public property
[Display(Name = "Created On")]
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime CreatedOn
{
            get
            {
                return (_createdOn == DateTime.MinValue) ? DateTime.Now : _createdOn;
            }
            set { _createdOn = value; }
}

Or in the View.

@Html.HiddenFor(model => model.CommentTime, new { @Value=System.DateTime.Now })

Or in the controller.

public ActionResult Index()
    {
        return View(new MyViewModel
        {
            Birth = DateTime.Now
        });
    }

If done in the controller and/or model you can use the html attribute of readonly like so.

You could use a custom editor template:

public class MyViewModel
{
    [UIHint("MyHiddenDate")]
    public DateTime Date { get; set; }
}

and then define ~/Views/Shared/EditorTemplates/MyHiddenDate.cshtml:

@model DateTime
@Html.Hidden("", Model.ToString("dd/MM/yyyy"))

and finally in your view use the EditorFor helper:

@model MyViewModel
@Html.EditorFor(x => x.Date)

This will render the custom editor template for the Date property of the view model and consequently render the hidden field with a value using the desired format.

UPDATE

The EditorFor html helper does not have overloads that take HTML attributes. In this case, you need to use something more specific like TextBoxFor:

<div class="editor-field">
    @Html.TextBoxFor(model => model.DateCreated , new 
        { disabled = "disabled", @readonly = "readonly" })
</div>

You can still use EditorFor, but you will need to have a TextBoxFor in a custom EditorTemplate:

public class MyModel
{
    [UIHint("DateCreated ")]
    public string DateCreated { ;get; set; }
}

Then, in your Views/Shared/EditorTemplates folder, create a file DateCreated .cshtml. In that file, put this:

@model string
@Html.TextBoxFor(m => m, new {  @readonly = "readonly" })

Upvotes: 2

Related Questions