【问题标题】:Accessing Route Value of Id inside a Partial View在局部视图中访问 Id 的路由值
【发布时间】:2011-06-16 18:27:21
【问题描述】:

我正在尝试从 PartialView 内部访问 id 的 Route 值。我有一个帖子,评论场景。我希望我的评论部分视图能够访问 PostId。

网址如下所示:

帖子/详细信息/2

现在,如何访问局部视图中的值 2?

更新:

我将 CommentsController 更改为以下内容:

 public ActionResult Add(string id,string subject,string name,string body)
{

}

但是现在当我调试它甚至没有进入 Add 方法。

更新 2:

我的局部视图如下所示:

<div class="title">Add Comment</div>

@using (Html.BeginForm("Add","Comments",FormMethod.Post))
{
    @Html.Label("Subject") 
    @Html.TextBox("subject")
    <br />
    @Html.Label("Name") 
    @Html.TextBox("name") 
    <br />
    @Html.Label("Body") 
    @Html.TextBox("body") 




    <input type="submit" value="submit" />                            
}

这里是控制器:

 public ActionResult Add(string id, string subject, string name, string body)

如果我从上述控制器操作中删除 id,那么它就可以工作。

【问题讨论】:

    标签: asp.net asp.net-mvc


    【解决方案1】:

    你可以从RouteData获取它:

    在网络表单中:

    <% 
        var id = ViewContext.RouteData.Values["id"];
    %>
    

    在剃刀中:

    @{
        var id = ViewContext.RouteData.Values["id"];
    }
    

    显示您的代码后,您的表单中似乎没有传递 id。所以修改如下:

    @using (Html.BeginForm("Add", "Comments", new { id = ViewContext.RouteData.Values["id"] }, FormMethod.Post))
    {
        ...
    }
    

    如果您愿意,也可以使用隐藏字段:

    @using (Html.BeginForm("Add", "Comments", FormMethod.Post))
    {
        @Html.Hidden("id", ViewContext.RouteData.Values["id"])
        ...
    }
    

    现在您应该在 Add 控制器操作中获取 id。

    【讨论】:

    • 无论如何要从 CommentsController 中获取它,还是我必须在 Comments 视图中获取它,然后将其放在隐藏字段中并将其发布到 CommentsController 的操作中?
    • @johndoe,如果您想在某个控制器上获取它,只需将其作为操作的参数:public ActionResult Foo(string id) { ... } 并且模型绑定器应该负责传递它。
    • @johndoe,您采取了哪些步骤来调用此操作?我无法猜测您在这里要做什么。请描述您的具体场景,提供相关代码sn-ps,...如果您需要帮助。
    • 对此我感激不尽!!我花了过去几个小时试图弄清楚如何传递 id
    【解决方案2】:

    在您的控制器内部,您可以将路由数据放入发送到视图的视图模型中;然后视图可以沿着它的视图模型(或它的一部分)传递给局部视图。理想情况下,您的视图(包括部分视图)应该只需要依赖其视图模型提供的数据来呈现。

    public ActionResult Add(string id, string subject, string name, string body)
    {
        return View(
            new AddedViewModel {
                Id = id,
                // etc...
            }
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多