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
The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.
ViewData, ViewBag, and TempData are used to pass data between controller, action, and views. To pass data from the controller to view, either ViewData or ViewBag can be used.
There are a number of ways in which you can pass parameters to action methods in ASP.NET Core MVC. You can pass them via a URL, a query string, a request header, a request body, or even a form.
On basis of data transfer mechanism ASP.NET MVC views are categorized as two types, Dynamic view. Strongly typed view.
In your View, at the very top:
@model Int32
Or you can use a ViewBag.
ViewBag.LinkableId = intval;
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With