Fairly new to MVC3 and I am doing a simple project for testing purposes. So I have encountered a slight problem which I would like your help about.
At the moment I have this code :-
<p>
@if (UserCanCreate)
{
@Html.ActionLink("Create New", "Create")
}
My question is, how can I populate the boolean value UserCanCreate from my controller? I tried creating a property in the Controller, but the View still does not see this.
Is there maybe a better way to do this?
Thanks for your help
UPDATED with ViewModel
@model IEnumerable<DBName.ViewModels.ProfileData>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@Html.ActionLink("Details", "Details", new { id=item.FantaTeamID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.FantaTeamID })
</td>
</tr>
}
How can I replace this code now? from where to get item.UserName?
Thanks
There are at least two different ways you can do it.
First one (better one) is using a Model to pass data. For that you should create a Model class:
and specify it at the beginning of your View (use typed view):
And, of course, in your controller action do the following:
Second (faster one, although not recommended): use ViewData collection to pass values.
For example, in your controller action do:
and your view will look like:
Also important: if you’re trying to secure some actions that way then do not forget to add some checks for permissions inside “Create” action code – otherwise any user will be able to execute it by just entering corresponding URL in browser address bar – even if the ActionLink is not present.
UPDATE
As for your comment – you seem to be mixing domain models with view models. Domain models are the ones that represent your database entities, while view models are the ones that should be used for presentation. Generally it’s controller’s job to convert objects from domain to view models and vice versa.
In your case EF models are domain models.
For ViewModel you should create a separate class which will aggregate your domain model instance and any additional properties you want – like UserCanCreate.
Example model class:
In your controller it will be:
and in view: