Question: Razor view stops working after encapsulating attribute

Question

Razor view stops working after encapsulating attribute

Answers 1
Added at 2017-09-07 19:09
Tags
Question

So I have this C# MVC project with some views in Razor.

If I change an existing field in my model to a property or vice-versa, any Razor view that references this field stops working and I get a System.MissingFieldException at run time, even though the field is still there. The view only works again if I make any change to it e.g. adding a blank space somewhere. For Example,

If I change this:

public class Test
{
   public List<string> myStrings = new List<string>();
}

To This:

public class Test
{
    private List<string> _myStrings = new List<string>();

    public List<string> myStrings
    {
        get
        {
            return _myStrings;
        }
        set
        {
            _myStrings = value;
        }
    }
}

Why does this happen? Is there a way to have the views refreshed automatically so I don't have to find every view that references that property and make changes to the view?

Answers to

Razor view stops working after encapsulating attribute

nr: #1 dodano: 2017-09-07 21:09

Is the Test class located in a different project/class library. Rebuild you solution once, because Changing a field into a property is a breaking change (MSDN). The Compiler will not throw an error upon changing a field to a property, because a property is used with the same syntax as a field. But internally they are different things. Different types of MSIL signature are generated for properties and fields (go through the first link). Property gets called from the client as a method call.

This chapter on Why Properties Matter from Jon Skeet's "C# in Depth" book is also worth a read.

Source Show
◀ Wstecz