What is the @ in a view and controller for?

Asked

Viewed 323 times

8

I program in PHP and I’m starting to learn how to program in C# ASP.Net MVC, but I’m having some questions:

  1. What is the purpose of @ (arroba) both in controller how much in the view ?
  2. What are these calls for { get; set; } that the staff put on model?

    public int id { get; set; } public string name { get; set; }

2 answers

9


What is the purpose of @ (arroba) both in controller how much in the view?

In the View, indicates to the Razor engine that the following code is to be interpreted by .NET. Can be used on a line:

@if (condicao) { ... }

Or it can serve as a block opening:

@{
    var minhaVariavel = ...;
}

In theory, the Razor engine interprets any . NET code, but the most commonly used ones are C# and VB.NET.

I do not recommend much use the second because business logic in View should be discouraged, since the View is for presentation, not for logic. It is important to know that the resource exists, but should not be used as in PHP.

What are these calls for { get; set; } that the staff put on model?

Are automatic properties (auto properties). It is a concise way of writing the following:

private int _id;
public int id { 
    get { return _id; }
    set { _id = value; } 
}

As the definition of properties is often used, this more streamlined writing saves programmer effort.

8

In the view using the rendering engine Razor it indicates that the following is a C# code and not HTML, and so it will need to be executed and the result of this execution is that it will be rendered as part of HTML. See all razor syntax. Use the minimum necessary.

In the controller is a escape form.

The public int id { get; set; } is a automatic property. This means that an internal member in the class will be created to hold the status of id and there will be two methods to access your content. These methods are called getter and Setter. But they are not called as methods, the syntax is that as if you were accessing a variable. It is the same as:

private int _id;
public int id {
    get { 
      return _id; 
    }
    set {
      _id = value; 
    }
}

There are advantages and disadvantages of choosing a property. In the model it is usually very advantageous to indicate which members should keep state.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.