首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ajax post不工作MVC 5

Ajax post不工作MVC 5
EN

Stack Overflow用户
提问于 2015-12-04 22:42:05
回答 3查看 12.7K关注 0票数 1

我试图将数据发布到控制器中,但似乎不起作用,我需要post在完成后将视图的内容包含到div中,但我不能完全实现它

下面是我的js函数:

代码语言:javascript
复制
function show(num) {
    $.ajax({
        dataType: "html",
        type: "POST",
        url: "Student/Schedule",
        data: { number: num },
        success: function (a) {
            // Replace the div's content with the page method's return.
            alert("success");
            $('#schedule').load(a);
        }
    });
}

这是我的控制器:

代码语言:javascript
复制
public ActionResult Schedule(String number)
{
    return View(number);
}

我是一个MVC和C#的新手,所以欢迎任何帮助。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-12-04 22:51:57

为了解决这个问题,你需要解决一些问题。

  • 将Url更改为"/Student/Schedule"

您正在使用"Student/Schedule"作为url,所以您正在尝试调用一个名为“”的操作。请将[HttpPost]添加到您的操作中。

  • return PartialView("Schedule", number);

当您使用return View(number)时,它使用数字字符串值作为视图名称。您应该显式传递视图名称和模型。

  • 使用$('#schedule').html(a);

最好在ajax调用中添加一个error函数,以便能够发现错误:

代码语言:javascript
复制
error: function (jqXHR, textStatus, errorThrown) { 
    alert(errorThrown); 
    //or you can put jqXHR.responseText somewhere as complete response. Its html.
}
票数 3
EN

Stack Overflow用户

发布于 2015-12-04 23:01:33

您的操作应返回局部视图,而不是视图。

将您的操作更改为:

代码语言:javascript
复制
[HttpPost]
// by the way use string instead of String
public ActionResult Schedule(string number) 
{
    return PartialView("_Schedule", number);
}

然后,您需要创建一个名为_Schedule.cshtml的局部视图。

此外,您需要将$('#schedule').load(a);更改为$('#schedule').html(a);,我建议您在ajax调用中使用Url.Action来设置url,如下所示:

代码语言:javascript
复制
function show(num) {
    $.ajax({
        dataType: "html",
        type: "POST",
        url: '@Url.Action("Schedule", "Student")',
        data: { number: num },
        success: function (a) {
            // Replace the div's content with the page method's return.
            alert("success");
            $('#schedule').html(a);
        }
    });
}
票数 1
EN

Stack Overflow用户

发布于 2015-12-05 00:09:34

我遇到了同样的问题,我所做的是将jquery.unobtrusive-ajax.js添加到我的脚本中

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34090839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档