【发布时间】:2017-11-29 10:18:07
【问题描述】:
我需要在局部视图中使用 ajax 来调用 mvc 控制器中的函数以返回计算。
仅供参考,我正在使用 MVC 5 和 Umbraco 7。
我目前在局部视图中有 ajax 代码(有时会希望将其移动到 js 文件中)。
这里是ajax代码:
function GetTime(name) {
var result = "";
$.ajax({
url: '/TimeDifference/GetTimeDifference',
//url: '@Url.Action("GetTimeDifference", "TimeDifference")',
type: 'GET',
//data: JSON.stringify({ location: name }),
data: ({ location: name }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
cache: false,
success: function (msg) {
result = msg;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
return result;
}
这里是控制器:
public class TimeDifferenceController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetTimeDifference(string location)
{
DateTime utc = DateTime.UtcNow;
string timeZoneName = GetTimeZoneName(location);
TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
TimeZoneInfo local = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
TimeSpan utcOffset = gmt.GetUtcOffset(utc);
TimeSpan localOffset = local.GetUtcOffset(utc);
TimeSpan difference = localOffset - utcOffset;
return Json(Convert.ToInt16(difference.TotalMinutes),JsonRequestBehavior.AllowGet);
}
}
上面的代码给了我一个 404 Not Found 错误:
Request URL:http://localhost:100/TimeDifference/GetTimeDifference?location=BVI&_=1511949514552
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:100
如果我使用: url: '@Url.Action("GetTimeDifference", "TimeDifference")'
@Url.Action("GetTimeDifference", "TimeDifference") 为 Null,因此它不会去任何地方。
我也试过了:
@Html.Hidden("URLName", Url.Action("GetTimeDifference", "TimeDifference"))
...
url: $("#URLName").val()
Url 仍为 Null。
我已经在 Global.asax.cs 中添加了用于路由的条目,即
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "TimeDifference", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
这似乎没有任何作用。
我已经解决了很多之前提出的问题,并根据建议进行了修改,但似乎没有任何效果。
因为我是新手,所以我确信我错过了一些非常简单的东西。
非常感谢, 呵呵
【问题讨论】:
-
我建议阅读UmbracoApiController。它会自动为您映射路线,并帮助您访问有用的东西,例如
UmbracoHelper。如果您难以让它工作,请说出来,我会发布一个答案来说明它是如何工作的。 -
@Harvey - 感谢您的回复,您对 UmbracoAPI 控制器很满意。
标签: ajax asp.net-mvc umbraco