1

I added the data annotation to the PurchaseAmount field [ReadOnly(true)],

Built the application, ran "Add-Migration New 1" in Package Manager,

then ran "Update-Database"

Nothing changed. The field on the page was still editable.

Can you help?

Model code

public class Investments
{
    public int ID { get; set; }
    ....
    [ReadOnly(true)]
    [DataType(DataType.Currency)]
    public double PurchaseAmount { get; set; }
}

Controller Code

@model StockHoldings.Models.Investments
....
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    ....
    <div class="form-group">
        @Html.LabelFor(model => model.PurchaseAmount, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.PurchaseAmount, new { id = "purchaseamountID", name = "PurchaseAmount", htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.PurchaseAmount, "", new { @class = "text-danger" })
        </div>
    </div>
    ....
}
DRL
  • 39
  • 3
  • Please note that the model-view-controller tag is for questions about the pattern. There is a specific tag for the ASP.NET-MVC implementation. –  Dec 19 '16 at 22:36
  • The `[ReadOnly]` attribute has nothing to do with how its rendered. Use `@Html.TextBoxFor(m => m.PurchaseAmount, new { @readonly="readonly", .... })` –  Dec 19 '16 at 22:38
  • Side note - remove your `new { name = "PurchaseAmount" }` NEVER attempt to override the `name` attribute - and fortunately you attempt does not work anyway. And why are you overiding the `id` attribute - its already `id="PurchaseAmount"` –  Dec 19 '16 at 22:46
  • Possible duplicate of [ReadOnly attribute doesn't work in ASP.NET MVC Models](http://stackoverflow.com/questions/14995577/readonly-attribute-doesnt-work-in-asp-net-mvc-models) –  Dec 19 '16 at 22:47
  • Stephen, thanks so much for your inputs which I value! Please try to be understanding as I am new to Stack Overflow and MVC. Thanks. – DRL Dec 20 '16 at 21:17

0 Answers0