开发者

asp.net mvc - inconsistent rendering of ActionLink

I have a controller which accepts URLs in the following two formats:

  • Network/AddOrEdit -> renders a blank form on a page to add a new network object
  • Network/AddOrEdit/[id] -> renders a page with prepopulated form to edit the network object with ID [id]

Obviously it's the same view being used in each instance - one of my design goals is to use the same view for adding 开发者_开发知识库and editing purposes.

The master page contains a link to the add page like this:

@Html.ActionLink("Add", "AddOrEdit", "Network")

Ordinarily this renders correctly as /Network/AddOrEdit.

However, when I am on the edit page (i.e. the current URL is in the format Network/AddOrEdit/[id]), then the Add link renders with that ID on the end - so the add link actually points to the edit page. This is not what I want!

So for some reason MVC seems to be allowing the current ID from the query string to interfere with the rendering of the ActionLink.

Any suggestions what I can do about this? :(


Your guessing is right. MVC routing mechanism may reuse route variables from the current request to generate outgoing route data. That's why the id parameter is populated from the current request. You should explicitely specify id when generating link

@Html.ActionLink("Add", "AddOrEdit", "Network", new { id = String.Empty }, null)

And when routing system sees route with optional id parameter, and route value with string.Empty, it generates link without id in the end


Tried this myself:

@Html.ActionLink("Add", "AddOrEdit", "Network", new { id = UrlParameter.Optional })

Apparently, this one works too.

@Html.ActionLink("Add", "AddOrEdit", "Network", new { id = String.Empty })

Hopefully this works for you too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜