在 MVC 4 路由中,我有如下路由,
RouteTable.Routes.MapRoute(
name: "Comments_InsertComment",
url: "{controller}/{action}/{parameters}",
defaults: new { controller = "Comments", action = "InsertComment", parameters = UrlParameter.Optional}
);
Controller 上的方法有这样的签名,
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 调用(有效)向 Controller 发布 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; }
}
并且参数在 javascript 中设置为,
var params = { ParentCommentId: null, CommentText: commentText, BlockReplies: null };
最佳答案
请尝试在 ajax 中使用此代码块
url: '@Url.Content("~/Comments/InsertComment")',
data: { parameters: params },
dataType: 'JSON'
希望对您有所帮助。
关于c# - 没有要求参数的 MVC 4 JSON 路由发布数据路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28144775/