I'm totally new at mvc razor, so please excuse my unfamilarity with this subject. If I understood well, it is the controller which gets the url parameter, like the following:
// Get: /User/23
public ActionResult(int? id) {
return View("User", id);
}
So basically, this ActionResult
gets the parameter in the url and sends it somewhere. But where?
Also, say I have a repository in which I return all the users in an IQueryable<>
class. If the id is not null it gets only the relevant result, if not, it gets the whole list.开发者_开发百科 Therefore, I'd like to return a list to the view and show the results. How can I do that? To ease the understanding I give the following example:
// I want to populate this list based on the id in the actionresult
@foreach(var u in MyList) {
name: @u.Name <br>
lastname: @u.LastName <hr>
}
return View
invokes a helper method in the base class, Controller
.
It will return a ViewResult
, with the parameter being the model passed to the view.
So if you want to pass through a list of User's, you would do this:
public ActionResult Users()
{
var users = _repository.FindAllUsers();
return View(users);
}
Note how i left out the View name, so the default convention will be to look for a View based on the action name, in this case Users.cshtml
. Always try and use convention over configuration - this is what makes MVC great.
@model IEnumerable<YourApp.Models.User>
@Html.DisplayForModel()
Shared\DisplayTemplates\User.cshtml
@Html.LabelFor(model => model.Name)
@Html.DisplayFor(model => model.Name)
@Html.LabelFor(model => model.LastName)
@Html.DisplayFor(model => model.LastName)
Note how i didn't use a foreach
loop - i use i custom display template, again - convention over configuration.
Whatever you return as the second parameter is the model passed into the view. You could then inherit the razor page in WebViewPage, or better, use the @model keyword. The data passed in is available within the page via the "Model" variable.
Good example of usage after that is at http://weblogs.asp.net/scottgu/archive/2010/10/19/asp-net-mvc-3-new-model-directive-support-in-razor.aspx
精彩评论