开发者

Accessing Route Value of Id inside a Partial View

I am trying to access the Route value of id from inside the PartialView. I have a Post, Comments scenario. And I want my Comments partialview to have access to the PostId.

The Url looks like the following:

Posts/Detail/2

Now, how can I access the value 2 inside the Partial View?

UPDATE:

I changed my CommentsController to the follow开发者_JAVA技巧ing:

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

}

But now when I debug it does not even step into the Add method.

UPDATE 2:

My partial view looks like the following:

<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" />                            
}

And here is the Controller:

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

If I remove id from the above controller action then it works.


You could fetch it from RouteData:

In WebForms:

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

In Razor:

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

After showing your code it seems that in your form you are not passing the id. So modify it like this:

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

or use a hidden field if you prefer:

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

Now you should get the id in your Add controller action.


Inside of your controller, you could put the route data in the view model that gets sent to the view; the view can then pass along its view model (or portions of it) to the partial view. Your views, including partial views, should ideally only need to rely on data provided by their view models to render.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜