C# 从 MVC 4 中的 URL 获取“Id”值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19424340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting "Id" value from the URL in MVC 4
提问by now he who must not be named.
My URL is something like,
我的网址是这样的,
localhost:19876/PatientVisitDetail/Create?PatientId=1
localhost:19876/PatientVisitDetail/Create?PatientId=1
I have to retrieve the PatientId
from the URL and pass it along the request.
我必须PatientId
从 URL 中检索 并将其传递给请求。
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.
根据下面杰森的评论,我试过了Request["SomeParameter"]
,它奏效了。但是,还有一个警告要避免这种情况。
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.
Create
我的控制器中有一个用于创建新患者的操作方法。
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.
所以,patientId
在这种情况下,我必须传递。
采纳答案by James
You are effectively circumventing the whole point of MVC here. Have an action which accepts PatientId
i.e.
您在这里有效地绕过了 MVC 的全部要点。有一个接受PatientId
即的动作
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.
这是MVC的方式。
回答by WannaCSharp
From your controller, you could put the PatientId
in a ViewBag
and access it from your View
从您的控制器中,您可以将PatientId
a放入ViewBag
并从您的视图中访问它
public ActionResult Create()
{
ViewBag.PatientId = 1;
return View();
}
View
看法
Html.ActionLink("Back", "Index", new { PatiendId = ViewBag.PatientId })