0

In my Controller MVC, I have an Action to show my Model (generic model with 3 fields [Code], [Libelle] and [IsActif]).

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
[ActionName("AfficheDetailMotifRejet")]
[AuthorizeRoleFilter(Roles = TypeRoles.Roles.ADMINISTRATEUR_NATIONAL)]
public ActionResult AfficheDetailMotifRejet([DefaultValue(Int64.MinValue)] Int64 id)
{
    DetailGeneric dg = new DetailGeneric { Id = id };

    if (id > 0)
    {
        MotifRejet s = _srvMotifRejet.Charger(id);
        Mapper.CreateMap<MotifRejet, DetailGeneric>();
        dg = Mapper.Map<MotifRejet, DetailGeneric>(s);
    }            

    return View("GererMotifRejet", dg);
}

If I send Int64.MinValue as Id, then my Model is showed empty, ready to be inserted. But when I show to Edit with an existant Id, I need to made the field [Code] in ReadOnly mode.

What is the best solution ?

I think about to add [ReadOnly(true)] attribute in dg.Code, but how to made this ?

However, I can made this with a javascript, but there is a risk, if user don't have javascript activated.

Thanks for your helping.

User.Anonymous
  • 1,719
  • 1
  • 28
  • 51
  • 2
    Attributes are constant values that are compiled with the code and stored in the dll itsself - which means you technically can't 'change' an attribute's value at runtime unless you generate and compile the code at runtime. You'll probably want to look for another way to achieve the same thing without focusing on the attributes. – Jason Haley Jun 21 '11 at 11:25

2 Answers2

2

You can't set attributes at runtime (e.g in "code").

Your best bet would be to create a view model which wraps the edit and create modes, then do 1 of two things:

1) Do an @if (Model.IsEditMode) check, and render out either @Html.EditorFor if true, or @Html.DisplayFor if false

2) Create a HTML helper, tied to the model, which inspects the model data and calls into one of the above helpers based on the same value.

Either way, you need some kind of "base" view model for the create and edit views if you want to make decisions accordingly.

RPM1984
  • 72,246
  • 58
  • 225
  • 350
0

I think it is possible to provide model metadata in run time using custom metadata provider, but that's wrong (solution would be too complex) approach to tackle this problem.

I would just ensure in model after http post that entity is editable and avoid rendering editing related stuff @ client side.

Community
  • 1
  • 1
Arnis Lapsa
  • 45,880
  • 29
  • 115
  • 195