问题描述
我想通过jQuery的Ajax方法,在我的.NET MVC应用程序提交表单。我已经设置了数据类型设置为JSON和将contentType为application / json的;字符集= UTF-8。在我的控制器动作,我返回一个JsonResult。
I am trying to submit a form via jquery's ajax method in my .net mvc application. I've set the dataType to json and the contentType to "application/json; charset=utf-8". In my controller action, I'm returning a JsonResult.
由于某些原因,JSON响应并没有得到正确处理,而是我得到一个对话框,保存文件,它里面的JSON对象。
For some reason, the JSON response doesn't get handled correctly and instead I get a dialog box to save a file with the JSON object inside of it.
$(document).ready(function() {
$("#editPageContentForm").submit(function() {
$.ajax(
{
type: "POST",
dataType: "json",
url: $("#editPageContentForm").attr("action"),
contentType: "application/json; charset=utf-8",
data: { ID: $("#id").val(), small_title: $("#small_title").val(), big_title: $("#big_title").val(), body: $("#body").val(), subheading: $("#subheading").val() },
success: function(result) {
alert('hi');
},
error: function(req, status, error) {
alert("Sorry! We could not receive your feedback at this time.");
}
}
);
})
在我的控制器动作,我有一个类似于:
In my controller action, I have something akin to:
public JsonResult Edit(int id, string small_title, string big_title, string subheading, string body)
{
return Json(new {success = true, message = "success"});
}
为什么反应不回来的JSON?
Why is the response not coming back as JSON?
推荐答案
它的是的回来为JSON。但是,因为你这样做的形式提交,浏览器期望的HTML。浏览器不知道如何在视觉上呈现的JSON,所以它会提示你保存吧。需要注意的是,在这一点上你的jQuery code不再运行,由于与表单的页面被卸载时,浏览器张贴。
It is coming back as JSON. But since you're doing this in a form submit, the browser is expecting HTML. The browser doesn't know how to visually render JSON, so it prompts you to save instead. Note that at this point your jQuery code is no longer running, because the page with the form was unloaded when the browser POSTed.
这不是完全清楚你的意图,但如果你想完全取代非Ajax提交与AJAX-只提交,请尝试更改您的code到:
It's not entirely clear what you intend, but if you want to completely replace the non-AJAX submit with an AJAX-only submit, try changing your code to:
$("#editPageContentForm").submit(function(event) {
event.preventDefault();
$.ajax(
{
type: "POST",
dataType: "json",
url: $("#editPageContentForm").attr("action"),
contentType: "application/json; charset=utf-8",
data: { ID: $("#id").val(), small_title: $("#small_title").val(), big_title:
$("#big_title").val(), body: $("#body").val(), subheading:
$("#subheading").val() },
success: function(result) {
alert('hi');
},
error: function(req, status, error) {
alert("Sorry! We could not receive your feedback at this time.");
}
} );
这篇关于.NET / MVC JSON响应打开对话框,保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!