这让我发疯!
我有一个使用以下脚本使用 Ajax 填充的视图。
function loadAcquisitions() {
var description = $("input#searchDescription").val();
var startDate = $("input#searchStartDate").val();
var endDate = $("input#searchEndDate").val();
$.ajax({
type: "POST",
dataType: "json",
url: "/Acquisition/Find",
data: { searchDescription: description, searchStartDate: startDate, searchEndDate: endDate },
success: function (jsonresults) {
$("tbody#acquisitionContent").find("tr").remove().end();
var pageCount = parseInt(jsonresults.length / pageSize);
var startItemIndex = currentPageIndex * pageSize;
var itemsToDisplay = pageSize + startItemIndex;
if ((jsonresults.length - startItemIndex) < pageSize) {
itemsToDisplay = jsonresults.length - startItemIndex + pageSize;
}
for (var i = startItemIndex; i < itemsToDisplay; i++) {
$("tbody#acquisitionContent").append('<tr>' +
'<td><a href="/Acquisition/Edit/' + jsonresults[i].AcquisitionID + '">Edit</a></td>' +
'<td>' + jsonresults[i].AcquisitionDescription + '</td>' +
'<td>' + jsonresults[i].AcquisitionDate + '</td>' +
'<td>$' + jsonresults[i].AcquisitionCost + '</td>' +
'<td>$' + jsonresults[i].InstallationCost + '</td>' +
'<td class="last">$' + jsonresults[i].DeliveryCost + '</td>' +
'</tr>');
}
$('#pageTitle').text('Page ' + (currentPageIndex + 1) + ' of ' + pageCount);
},
error: function (c, b, a) {
alert(a);
}
});
}
请注意,链接是使用以下行生成的:
'<td><a href="/Acquisition/Edit/' + jsonresults[i].AcquisitionID + '">Edit</a></td>'
链接标签似乎生成正确,形式为
/Acquisition/Edit/123
在控制器中,我有以下名为“编辑”的函数,如下所示:
public ActionResult Edit(int acquisitionID)
{
Acquisition acquisition = Acquisition.Get(acquisitionID);
return View(acquisition);
}
然后,在 global.asax 中,我为“编辑”定义了一条路线,如下所示:
routes.MapRoute(
"EditAcquisition",
"{controller}/{action}/{acquisitionID}",
new { controller = "Acquisition", action = "Edit"}
);
我已经尝试更改控制器中的“编辑”功能以接受可以消除错误的可为空的 int(int?)采集ID - 但不会改变将空值传递给控制器“编辑”功能的事实来自 Ajax 代码生成的链接。
任何帮助将不胜感激!
谢谢!
更新:
当我更新 global.asax 并添加“acquisitionID”作为参数时,如下所示:
routes.MapRoute(
"EditAcquisition",
"{controller}/{action}/{acquisitionID}",
new { controller = "Acquisition", action = "Edit", acquisitionID = 0 }
);
该应用程序的行为非常不同,因为导航链接现在都附加了“索引”。
/Acquisition/
变成
/Acquisition/Index
更新:
这是 global.asax 的 RegisterRoutes 方法
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"EditProperty",
"{controller}/{action}/{propertyID}",
new {controller = "Property", action = "Edit"}
);
routes.MapRoute(
"EditAssignee",
"{controller}/{action}/{assigneeID}",
new {controller = "Assignee", action = "Edit"}
);
routes.MapRoute(
"EditAcquisition",
"{controller}/{action}/{acquisitionID}",
new {controller = "Acquisition", action = "Edit"}
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
}