Question

Two objects, what is the difference between how these object definitions? This threw me for a while because this particular object is used as a parameter to an MVC controller action, and when the values from the view are POSTed, the first version was able to model bind to the values being posted back. The second did not.

//version 1
public class SecurityViewModel
{
    public string Identifier { get; set; }
    public string CrdId { get; set; }
}

// version 2
public class SecurityViewModel
{
    public string Identifier;
    public string CrdId;
}

Using either version I can still do

SecurityViewModel mymodel = new SecurityViewModel();
mymodel.Identifier = "this";
mymodel.CrdId = "that";

So obviously even without the auto-implemented get and set I can still get and set the values of the properties.

However...

Version One has auto-implemented properties, version two just has the properties declared. Both allow you to set/get the values of those properties when the objects are created, but version one is the only one that will work with modelbinding on a controller method defined as...

public ActionResult Index(SecurityViewModel myModel)

Can anyone elaborate on this?

Was it helpful?

Solution

MVC binds to properties. The second version:

public class SecurityViewModel
{
    public string Identifier;
    public string CrdId;
}

uses fields, not properties.

See also What is the difference between a Field and a Property in C#?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top