开发者

What does Model.(Variable) do?

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 ')'

开发者_JAVA百科

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?


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.


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.


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜