【发布时间】:2015-01-26 04:22:48
【问题描述】:
在 MVC 4 路线中,我有如下路线,
RouteTable.Routes.MapRoute(
name: "Comments_InsertComment",
url: "{controller}/{action}/{parameters}",
defaults: new { controller = "Comments", action = "InsertComment", parameters = UrlParameter.Optional}
);
控制器上的方法有这样的签名,
public ActionResult InsertComment(AddParameters parameters) {
//parameters are passed in via jquery ajax post data
}
我像这样在 ajax 中调用它们,
$.ajax({
type: 'POST',
url: '/Comments/InsertComment/null',
data:params,
dataType: "json",
error: function (err) {
alert("error - " + err);
},
success: function (data) {
console.log(data);
alert('Your comment was added!');
}
});
我遇到的问题是我必须在 url 中指定 /null 或 /anything ,否则找不到它。当我希望它只是 /Comments/InsertComment 然后是帖子数据时。
我已经解决了我可以在这里找到的大多数类似的路由问题,但没有一个是通过 ajax 调用(有效)将 json 对象发布到控制器......
我尝试将 {parameters} 设置为 {id} 并设置 id = UrlParameter.Optional。我试过把它完全排除在外。我什至尝试过 paramters = UrlParameter.Optional。
而且我很确定它不匹配任何其他路线。
编辑:
AddParameters 定义为:
public class AddCommentParameters
{
public string ParentCommentId { get; set; }
public string CommentText { get; set; }
public string BlockReplies { get; set; }
}
并且params在javascript中设置为,
var params = { ParentCommentId: null, CommentText: commentText, BlockReplies: null };
【问题讨论】:
-
必须是
url: '/Comments/InsertComment',(或者更好的url: '@Url.Action("InsertComment", "Comments")',params是什么(在data:params中)?以及typeofAddParameters的属性是什么?-他们需要匹配为了绑定 -
我用请求的详细信息更新了我的问题。我不使用 @Url.Action... 的原因是 javascript 是一个独立文件。我有一个注册路由实用程序,可以使用评论系统在任何网站上调用。我也在使用'/Comments/InsertComment/null',因为如果我最后不指定参数,它就不起作用,无论我指定什么,我只需要指定一些东西。
-
我确实找到了处理它的默认路由,所以我将其更改为更具体并且不处理 cmets,但问题仍然存在。
-
处理单独的 js 文件问题的最佳方法是在触发调用的主视图元素中使用数据属性,例如
<button data-url="@Url.Action(..) ...>并在脚本中使用var url = $(this).data('url');获取它。至于需要附加/null,那应该不一定,所以如果url: '/Comments/InsertComment'不起作用,还有其他东西在起作用。 -
摆脱我的测试应用程序中的默认路由似乎已经修复了它。 /Comments/InsertComment 现在正在工作。我只是想弄清楚为什么控制器设置为 Main 且操作设置为 {index} 的 {controller}/{action} 会触发一个名为 Comments 的控制器和一个名为 InsertComment 的方法。
标签: c# jquery asp.net-mvc-4 http-post asp.net-mvc-routing