我应该如何格式化路径,以便它与 jQuery 中的 MVC 路由一起使用?我正在返回 Json,与另一个 SO post 非常相似。本地一切都运行良好,但部署起来却失败了。查询运行,但检查 firebug 看起来 jQuery.Get() 的 Success 回调没有触发。
最新更新
我现在遇到的唯一问题是特殊字符。每当我通过一个“。”或“@”作为 MVC 路由的一部分,我收到 404。删除这些特殊字符也会删除错误。您可以在下面看到 Controller 和路由逻辑。
每当我传递“.”时作为它轰炸的 URL 的一部分。 句号怎么了?
查询的形式为 /服务/索引/{电子邮件} -
EG 损坏/Service/Index/bmackey@foo.com (404)
工作 E.G./Service/Index/bmackeyfoocom (200)
旧东西(供引用)
我尝试了“/Service/Index/email”、“../Service/Index/email”、“../../Service/Index/email”
,但没有任何效果。
$email.blur(function ()
{
var email = $(this).val(); // grab the value in the input
var url = '@Url.Action("Index", "Service")'; //this is calling MVC page, not normal aspx so I can't pass it as a query param (at least as far as I am aware)
$.get(url + '/' + email.toString(),
更新
我停止对 URL 进行硬编码。本地运行完美运行。当我在 DEV 服务器上运行时,仍然出现 404 错误。该网址看起来正确。当我传递字符串值时,我收到 404 错误,但如果我将参数更改为 int,我会收到返回的“null”(带引号)。这让我相信我的 Controller 实现或路由有问题:
public ActionResult Index(string email)
{
string emailAddress = email;
GetActiveDirectoryInformation adInfo = new GetActiveDirectoryInformation();//calls entity framework
Common_GetAdInfo_Result result = adInfo.Lookup(email: emailAddress);
string jsonResponse = System.Web.Helpers.Json.Encode(result);
return Json(jsonResponse,JsonRequestBehavior.AllowGet);
}
全局.asax
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Service",
"Service/Index/{email}",
new { controller = "Service", action = "Index", email = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
最佳答案
从不像这样的硬编码 URL:
var url = '/Service/Index/' + email.toString();
处理 URL 时始终使用 URL 帮助器:
$email.blur(function () {
var email = $(this).val(); // grab the value in the input
var url = '@Url.Action("Index", "Service")';
$.get(url, { id: email.toString() }, function(result) {
// ...
});
});
无论您的应用程序部署在何处,URL 帮助程序都将始终生成正确的 URL。
如果这是一个单独的 javascript 文件,您无法在其中使用服务器端代码,您始终可以在输入字段上使用 HTML5 data-*
属性:
@Html.TextBoxFor(x => x.Email, new { data_url = Url.Action("Index", "Service") })
然后在单独的 javascript 文件中:
$email.blur(function () {
var email = $(this).val(); // grab the value in the input
var url = $(this).data('url');
$.get(url, { id: email.toString() }, function(result) {
// ...
});
});
关于c# - 与 MVC 3 中的路由配合使用的 URL 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5358223/