Url.Action怎么能已经知道没有我的routevalues​​设置呢? [英] How can Url.Action already know the routevalues without me setting them?

查看:301
本文介绍了Url.Action怎么能已经知道没有我的routevalues​​设置呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个jquery职位,一个MVC动作。行动返回与(例如)n = 123 code是仍处于早期阶段,一个JSON的结果,但我很惊讶地发现,Url.Action(行动,控制器)正在建设一个ur​​l完成与我从JSON的返回的ID。这是魔术?我找不到文件,指出它做到这一点。

I'm doing a jquery post to an MVC action. The action returns a json result with (for example) Id = 123. Code is still in early stage, but I was very surprised to find out that Url.Action("action", "controller") is building a url complete with the id I returned from Json. Is this magic? I couldn't find documentation that says it does that.

// how I assumed it would need to be accomplished
// redirects to "Controler/Action/123123" where data = { id = 123 }
$.post(saveUrl, json, function (data) {
    var detailsUrl = "@Url.Action("Action", "Control")" + data.id;
    window.location = detailsUrl;
});

// rewritten without adding id to the route, not sure how this works...
// redirects to "Controler/Action/123" where data = { id = 123 }
$.post(saveUrl, json, function (data) {
    var detailsUrl = "@Url.Action("Action", "Control")";
    window.location = detailsUrl;
});

仅供参考,这里是行动:

Just for reference, here is the action:

[HttpPost]
public ActionResult Save(Model model)
{
    return new JsonResult { Data = new { id = 123 }};
}

所以我想我的问题是,这是由设计?它是如何知道有什么用?

So I guess my question is, is this by design? How does it know what to use?

正如在应答,Url.Action有权访问现有routevalues​​和将尝试重新使用它们。为了解决这个问题我已经使用下面稍微哈克的解决方案:

As pointed out in the answer, Url.Action has access to existing routevalues and will attempt to reuse them. To get around this I have used the slightly hacky solution below:

var detailsUrl = "@Url.Action("Action", "Control", new { id = ""})" + "/" + data.id;

这清除了路由值,这样我可以在客户端上附加新的。遗憾的是,传递null或新{}作为RouteValues​​到Url.Action不克服这一点。一个更好的方法可能是创建另一个动作助手,保证没有routevalues​​附会。 Alternativly,也有Url.Content,但你将失去在IDE中动作/控制器的接线这样做。

This clears out the route values so that I can attach new ones in on the client side. Unfortunately, passing null or new {} as RouteValues to Url.Action does not overcome this. A nicer approach may be to create another Action helper that guarantees no routevalues will be attached. Alternativly, there is also Url.Content, but you will lose the Action/Controller wiring in the IDE doing this.

推荐答案

的的 UrlHelper (这是网​​址类型)的访问路径数据被用于访问的当前动作。它会尝试并使用这些值来填写必要的路由值给你,除非你指定,否则它们。

The UrlHelper (which is the type for Url) has access to the route data that was used to access the current action. It will try and use these values to fill in the necessary route values for you, unless you otherwise specify them.

这篇关于Url.Action怎么能已经知道没有我的routevalues​​设置呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆