【问题标题】:Getting "Id" value from the URL in MVC 4从 MVC 4 中的 URL 获取“Id”值
【发布时间】:2013-10-25 19:15:42
【问题描述】:

我的网址是这样的,

localhost:19876/PatientVisitDetail/Create?PatientId=1

我必须从 URL 中检索 PatientId 并将其传递给请求。

我试过了,

    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'

我又试了,

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

编辑:

根据下面 Jason 的评论,我尝试了 Request["SomeParameter"] 并且成功了。但是,也有一个警告要避免这种情况。

任何想法如何在我的场景中避免这种情况?

我的场景:

我的控制器中有一个Create 操作方法用于创建新患者。

但是,我需要回到最后一页,

如果我给出类似的东西,

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


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

public ActionResult Index(int patientId = 0)

所以,在这种情况下,我必须传递patientId

【问题讨论】:

  • 因为PatientId是一个查询字符串参数,看看这个:stackoverflow.com/questions/2888105/…
  • @JasonEvans:感谢您的链接。有效。但是,我也看到了一个警告,即do not access the url parameters in the view?。在我的情况下,如何避免这种情况?

标签: c# url asp.net-mvc-4 .net-4.0 routing


【解决方案1】:

您在这里有效地绕过了 MVC 的全部要点。有一个接受PatientId 的操作,即

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

然后在您看来使用该值,例如

@model int

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

这是MVC方式。

【讨论】:

  • 清洁解决方案。谢谢
  • 完美!我在这里找到了整洁干净的解决方案。谢谢! @詹姆斯
【解决方案2】:

在您的控制器中,您可以将 PatientId 放入 ViewBag 并从您的视图中访问它

public ActionResult Create()
{

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

查看

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

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 2020-09-08
    相关资源
    最近更新 更多