无法使用Ajax ASP.NET Core MVC更新部分视图 [英] Can't Update Partial View With Ajax ASP.NET Core MVC
问题描述
我想用Ajax更新我的部分视图,但是由于某些原因,它不起作用.如果我使用加载方法(并注释ajax代码),则它可以工作.这是我的代码:
I want to update my partial View with Ajax, but for some reason, it doesn't work. If I use load method (and comment ajax code), it works. this is my code:
这是我的主要观点:
@model IEnumerable<WebApplicationMVC.Models.Test>
@{
ViewData["Title"] = "Testing";
}
<div id="partial">
@await Html.PartialAsync("Question", Model.ToList()[0])
</div>
<input type="button" id="b" value="next" class="btn btn-default" />
<script>
$("#b").click(function () {
//this code doesn't work
$.ajax({
url: 'Test/Question',
type: 'GET',
contentType: "application/json; charset=utf-8",
data: { id: '@Model.ToList()[1].ID' },
dataType: "json",
success: function (result) {
$("#partial").html(result);
}
});
//this code works
@*$("#partial").load('@Url.Action("Question","Test",new { id=Model.ToList()[1].ID })');*@
});
这是我的问题操作方法int Test 控制器:
this is my question action method int Test controller:
public IActionResult Question(int id)
{
return View(Methods.GetTestById(id));
}
我有什么错误?
推荐答案
您已指定dataType: "json",
,但是您的方法返回的是视图(html),而不是JsonResult
,因此会引发异常.
You have specified dataType: "json",
but your method returns a view (html), not JsonResult
so an exception is being thrown.
要么省略dataType
选项(该函数将根据响应进行计算),要么将其更改为dataType: 'html'
Either omit the dataType
option (the function will work it out based on the response) or change it to dataType: 'html'
此外,您可以删除contentType
选项.您正在制作一个没有主体的GET,因此将其忽略(如果它是POST,则由于未对数据进行字符串化,您的方法也会失败).
In addition, your can delete the contentType
option. You are making a GET which has no body so its ignored (and if it was a POST, your method would also fail because you have not stringified the data).
您的网址也应为/Test/Question
(正斜杠),并且您应始终使用@Url.Action()
方法生成网址
Your url should also be /Test/Question
(leading forward slash), and you should always use the @Url.Action()
method to generate the url
您的功能应该是
$.ajax({
url: '@Url.Action("Question","Test")',
type: 'GET',
data: { id: '@Model.ToList()[1].ID' },
success: function (result) {
$("#partial").html(result);
}
});
这篇关于无法使用Ajax ASP.NET Core MVC更新部分视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!