angelPL
angelPL

Reputation: 73

ASP.NET MVC Passing action parameter to the view

Let's say that I have a Action method like this:

public ActionResult Page(int? id)
{
}

The question is, how can I read 'id' parameter in View?

Upvotes: 1

Views: 3628

Answers (2)

Tejasvi Hegde
Tejasvi Hegde

Reputation: 2922

You can access parameters from Request in view as below

Request.Params["id"]

Upvotes: 0

Johan
Johan

Reputation: 8276

Your code won't build successfully, until you return a view like this

public ActionResult Page(int? id)
{
    return View();
}

and because you want to return id to your view you can do Simple object

public ActionResult Page(int? id)
{
    return View(id);
}

Just remember to accept the new value in your view, by dong the following at the top (very first line)

@model int?

ViewModel approach

public class MyViewModel
{
    public int? Id { get; set; }

    //Other properties here
}

 public ActionResult Page(int? id)
 {
     var myViewModel = new MyViewModel()
     {
         Id = id
     };
     return View(myViewModel);
 }

and then in your view

 @model MyViewModel

Upvotes: 1

Related Questions