http://localhost:53435/Blog/BlogIndex?title=blog+title&seo=seo&content=%3Cp%3Econtent%3C%2Fp%3E%0D%0A
网址如上
当我单击“保存”按钮时,页面会刷新并且网址如下
我不想要它,我该如何修复它??
我的 Controller 代码
try
{
Blog addModel = new Blog();
content = content.Replace("<p>", "").Replace("</p>", "");
addModel.BlogPictureURL = pictureData;
addModel.BlogContent = content;
addModel.BlogPictureSEO = seo;
addModel.BlogTitle = title;
addModel.BlogDate = DateTime.Today;
addModel.BlogViewCount = 0;
db.Blog.Add(addModel);
db.SaveChanges();
var lastID = db.Blog.OrderByDescending(x => x.ID).Take(1).FirstOrDefault().ID;
foreach (var item in Tags)
{
Tags newTag = new Tags();
newTag.TagsName = item;
newTag.BlogID = lastID;
db.Tags.Add(newTag);
}
db.SaveChanges();
return RedirectToAction("BlogIndex", "Blog");
}
catch
{
return RedirectToAction("Error", "Admin");
}
我的ajax代码
function SaveAllData() {
var blogFile;
var elem = $(".dz-details").find("img");
blogFile = elem[0].getAttribute("alt");
var elemData = $("#tags").val();
elemData = elemData.split(",");
$.ajax({
type: "POST",
url: "/Blog/AddBlog",
datatype: "json",
traditional: true,
data: {
title: $("#title").val(),
seo: $("#seo").val(),
content: CKEDITOR.instances.content.getData(),
Tags: elemData,
pictureData: blogFile
}
});
}
如果我在没有ajax post的情况下执行此操作,则没有问题 但是用ajax做错了
最佳答案
看起来您的表单仍在执行正常的表单提交而不是 ajax post。当您有一些 javascript 代码在单击表单的提交按钮时执行 ajax 提交,但忘记停止默认行为(即单击提交按钮时的表单提交)时,就会发生这种情况。从您发布的网址来看,您的表单方法也是 GET,它通过查询字符串提交数据。
您只需确保不会让默认行为发生。
这是将点击事件绑定(bind)到按钮的简单方法
<button type="submit" class="btn btn-primary" style="float:right" id="btnSubmit">
和js代码
function SaveAllData() {
// your existing code for the ajax call
}
$(function(){
$("#btnSubmit").click(function(e){
e.preventDefault(); // This will prevent the default form submit
SaveAllData();
});
});
另外,如果是ajax表单提交,返回RedirectResult是没有意义的。您可以考虑返回一个 json 结构,其中包含要导航到的 url 值(如果需要)。
关于javascript - ajax post之后mvc url太长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41910844/