Home > DeveloperSection > Forums > Access to a variable from a view in another view
Ankit Singh

Total Post:341

Points:2389
Posted on    December-23-2013 2:06 AM

 ASP.Net ASP.Net 
Ratings:


 1 Reply(s)
 611  View(s)
Rate this:

I have the following problem with applpication:

Index.cshtml:

@model IEnumerable<ForestryManagement.Models.Forestry>

 @foreach (var forestry in Model)

    {

        <li>@Html.ActionLink(forestry.Name, "Index12", new {tree = forestry.ForestryID})

    }

When you click on one Forestry (ActionLink), you will be redirected to the Index12, where the trees from these Forestry are listed

Index12.cshtml:

@model IEnumerable<ForestryManagement.Models.Tree>

@foreach (var item in Model) {

    <tr>

        <td>

            @Html.DisplayFor(modelItem => item.treeName)

        </td>

        </tr>

@Html.ActionLink("Create new Tree", "Create", new { id = **??????**})

Now, when i will create another tree in this forestry, i need the ID from the forestry on my Index12.cshtml page for the ActioLink



Pravesh Singh

Total Post:411

Points:2881
Posted on    December-23-2013 4:53 AM

Hi Ankit,

Create a view model for tree listings, like so:

public class TreeListingViewModel

{

    public int ForestryId { get; set; }

    public IEnumerable<TreeViewModel> Trees { get; set; }

}

Note: Prefer creating a TreeViewModel instead of just using your Tree data entity to reduce the dependency between your view and your data model (and also increase security as people can quite easily inject properties into your database if you expose your data entities directly to your view).

Pass that to your view instead:

@model TreeListingViewModel

@Html.ActionLink("Create new Tree", "Create", new { id = Model.ForestryId })


Don't want to miss updates? Please click the below button!

Follow MindStick