Reputation: 15662
Okay, so I've got this code:
public ActionResult Welcome(string name = "", int numTimes = 1)
{
var viewModel = new WelcomeViewModel
{
Message = "Hello " + name,
NumTimes = numTimes
};
return View(viewModel);
}
public class WelcomeViewModel
{
public string Message { get; set; }
public int NumTimes { get; set; }
}
and the view in Welcome() is:
<h2>Welcome</h2>
<% for(int i = 0; i < Model.NumTimes; i++) {%>
<h3><%: Model.Message; %></h3>
<%} %>
Firstly, when I run this, I get an error when running .../Welcome?name=Scott&numtimes=4 saying that in the line
<h3><%: Model.Message; %></h3>
it expects ')'
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS1026: ) expected
why is this?
Secondly what is this whole Model thing? What does it do?
Upvotes: 1
Views: 419
Reputation: 77530
In addition to the misplaced semicolon, make sure your view is defined to inherit from ViewPage<WelcomeViewModel>
. This specifies the type that Model
has within the view, allowing the compiler to resolve its members (Message
, NumTimes
).
Upvotes: 0
Reputation: 700342
It's because the <%: Model.Message; %>
translates (basically) into:
Response.Write(Model.Message;);
As you see, the semicolon should not be there. The compiler expects the ending parentheses before there is a semicolon, hence the error message.
The "Model thing" is the M in MVC. The Model is the data that the View displays. Each view has a single Model, so the Model contains all the data that the View needs.
Upvotes: 2
Reputation: 26766
With regards to your second question, MVC is a way of separating the logic (in your controller) from the presentation (in your view).
You use the controller to generate a model which contains all the information required by the view.
Eg for a form, the model would have a field for each input. For a table, it would have an IEnumerable<SomeRowClass>
etc...
The view itself should do as little processing as possible - simple if statements and loops. all actual logic should be constrained to the controller.
One way to think of it is that a developer writes the controller, a designer writes the view and they collaborate for what goes in the model - designer says "I need to know X,Y,Z" - so the developer adds them to the model and populates the fields as appropriate
As mentioned in the other answer, the semicolon after Model.Message
is superfluous.
Upvotes: 0
Reputation: 27411
I think you don't need to put the semi-colon after Model.Message
.
Model is the reference to what you supplied to your view, in your controller. That's the same instance as what you type return View(viewModel);
in your controller.
Upvotes: 2