20

I have a controller which calls a view. Is there a way I can pass just an integer to my view an be able to use that integer in my view with razor code?

Here is my method in my controller:

public ActionResult Details(int linkableId)
{
    return View(linkableId);
}

After returning my view, can I access just this int using razor code like this or something:

@linkableId
tereško
  • 57,247
  • 24
  • 95
  • 149
DannyD
  • 2,530
  • 15
  • 45
  • 65
  • 2
    Use the dynamic collection `ViewBag` In the controller: `ViewBag.linkableId = 123123` in the view: `@ViewBag.linkableId` – asawyer Aug 07 '13 at 14:03

3 Answers3

29

In your View, at the very top:

@model Int32

Or you can use a ViewBag.

ViewBag.LinkableId = intval;
Lews Therin
  • 10,819
  • 4
  • 44
  • 69
  • My preference is I tend to go for the `ViewBag` approach when there is only one property passed into the view that does not need a viewmodel. Like in the example above this allows the view to be more readable, meaning I can see what @model really is without tracing it back to the controller to see it's a LinkableId in this example. – David B Oct 16 '20 at 14:15
11

Use ViewBag.

public ActionResult Details(int linkableId)
{
    ViewBag.LinkableId = linkableId;
    return View();
}

and then in your view:

@ViewBag.LinkableId 

This question may also help: How ViewBag in ASP.NET MVC works

Community
  • 1
  • 1
Fiona - myaccessible.website
  • 14,071
  • 15
  • 78
  • 115
  • I've never been a fan of Viewbags because they're just black holes you can put anything into. But they are so very easy to use. – I_Khanage Oct 14 '16 at 09:57
7

In your View, at the very top:

@model Int32

then use this in your view, should work no problem.For example:

<h1>@Model</h1>

Something else that I want to add is is your controller you should say something like this :

return View(AnIntVariable);
Ali Mahmoodi
  • 590
  • 7
  • 10