简体   繁体   中英

Does a model need to be explicitly passed to a view if the model is strongly bound to the view?

I have an example from a project I'm working on in which a particular model is passed on to the view from the controller, like this:

result = View(stu)           //stu is an object of type Student
  //
//
return result;

In that particular view, at the top I have @model Project.Models.Student and I have textboxes which bind the information entered to the model. However, in another controller I have another method that has the following code:

//
//
result = View();

//

and the view for this has @model.Project.Models.Login , but I can still bind things to the model from this view just like in the other view (eg, I have something like:

@Html.TextBoxFor(model => model.login_name, new { maxlength = "30" })

I didn't pass a model to the view like I did in the first method, and yet it seems to have the same functionality. If I am using @model at the top of the view, does that mean that it is not necessary to explicitly pass a model object as a parameter from the controller method?

If you declare @model at the top of your cshtml page, then your page expect to get model of the type you have declared. Of course you can choose not to use a model in your page, and in this situation your declare is useless. In addition you can declare a model, but don't send any object to the view. If you send an object, it must be the same type as you declare in @model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM