Getting "Id" value from the URL in MVC 4

My URL is something like,

localhost:19876/PatientVisitDetail/Create?PatientId=1

I have to retrieve the PatientId from the URL and pass it along the request.

I tried,

    Url.RequestContext.Values["PatientId"] => System.Web.Routing.RequestContext does not contain a definition for 'Values' and
no extension method 'Values' accepting a first argument of type 'System.Web.Routing.RequestContext'

Again I tried,

RouteData.Values["PatientId"]  => an object reference is required for the non static field, method
or property 'System.Web.Routing.RouteData.Values.get'

EDIT:

Based on the Jason's comment below, I tried Request["SomeParameter"] and it worked. But, there is also a warning to avoid that.

Any ideas how to avoid this for my scenario ?

My scenario:

There is a Create action method in my controller for creating a new patient.

But, I need to go back to the last page,

If I give something like,

 @Html.ActionLink("Back to List", "Index") 


=> this wont work because my controller action method has the following signature,

public ActionResult Index(int patientId = 0)

So, I must pass along the patientId in this case.

Upvotes: 1

Views: 31148

Answers (2)

James
James

Reputation: 82096

You are effectively circumventing the whole point of MVC here. Have an action which accepts PatientId i.e.

public ActionResult Create(int patientId)
{
    return View(patientId);
}

Then in your view use that value e.g.

@model int

@Html.ActionLink("Back", "LastAction", "LastController", new { patientId = @Model })

This is the MVC way.

Upvotes: 7

WannaCSharp
WannaCSharp

Reputation: 1898

From your controller, you could put the PatientId in a ViewBag and access it from your View

public ActionResult Create()
{

    ViewBag.PatientId = 1;
    return View();
}

View

Html.ActionLink("Back", "Index", new { PatiendId = ViewBag.PatientId })

Upvotes: 2

Related Questions