Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在MVC中传递Ajax post中的参数_Javascript_Ajax_Asp.net Mvc 5 - Fatal编程技术网

Javascript 在MVC中传递Ajax post中的参数

Javascript 在MVC中传递Ajax post中的参数,javascript,ajax,asp.net-mvc-5,Javascript,Ajax,Asp.net Mvc 5,我正在尝试将ID参数从视图传递到选定行上可用的单击删除链接上的控制器 简化视图布局 @using (Html.BeginForm("#", "Schedule", FormMethod.Post, htmlAttributes: new { @class = "floating-labels" })) { @Html.AntiForgeryToken() <a href="#"

我正在尝试将ID参数从视图传递到选定行上可用的单击删除链接上的控制器

简化视图布局

    @using (Html.BeginForm("#", "Schedule", FormMethod.Post, htmlAttributes: new { @class = "floating-labels" }))
    {
    @Html.AntiForgeryToken()

   <a href="#" onclick="DeleteSchedule(1);">Delete</a>
    }
<script type="text/javascript">
    function DeleteSchedule(id) {
        if (confirm('Are you sure you want to delete this Schedule?')) {
            $.ajax({
                type: "POST",
                url: '@Url.Action("Delete", "Schedule", new { id = "id" })',
                contentType: "application/json",
                data: { id },
                async: true,
                cache: false,
                success: function (result) { success(result); }
            });
        }
        return false;
    }

    function success(result) {
        $("#ScheduleList").html(result);
    }
</script>
但点击一个删除链接,我得到下面的错误和代码并没有击中控制器的行动


我无法找出我犯了什么错误…

读取请求很可能正确发送的错误,并且存在500响应中提到的内部服务器错误,因此请检查控制器中的代码

试试这个,您正在c代码上访问一个javascript变量,您不能这样做。 如果正确,请标记为答案

function DeleteSchedule(id) {
        if (confirm('Are you sure you want to delete this Schedule?')) {
             var url = '@Url.Action("Delete", "Schedule")?id=' + id;
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: { id },
                async: true,
                cache: false,
                success: function (result) { success(result); }
            });
        }
        return false;
    }

我认为上面的答案都不能解决这个问题。首先,我将替换您的目标url:

url: '@Url.Action("Delete", "Schedule", new { id = "id" })',

(将“id”替换为传递给视图的模型中的实际id变量)。 请注意浏览器的响应如何告诉您,您要发布到的url是计划/删除/id。也就是说,我不确定在这种情况下是否需要RouteValue(参数
new{id=…}
)。这是一个POST操作,操作参数不会来自route,除非由属性routing指定(即操作上的
[路由(~/Schedule/Delete/{id}”)]
属性)

我认为您的post操作失败了,因为它试图将“id”字符串解析为int

其次,我将更改ajax调用的数据属性,并包含防伪令牌。仅仅因为您将单击事件绑定到的锚元素位于带有
@Html.AntiforgeryToken()
的表单中,并不意味着生成的令牌将发布到ajax请求中。您实际上并没有提交/发布表单,您只是单击一个按钮

应该是这样的

data: { 
'id': id,
'__RequestVerificationToken': $('[name="__RequestVerificationToken"]').val()
}

这是我在本地测试的实现,它正在工作

ScheduleController类:

公共类ScheduleController:控制器
{
[HttpPost]
[ValidateAntiForgeryToken]
公共IActionResult Delete(int id)
{
返回Ok(id);
}        
}
发送post请求的页面:


@Html.AntiForgeryToken()
函数DeleteSchedule(id){
如果(确认('您确定要删除此计划吗?')){
var uri='/Schedule/Delete?id='+id;
var-tokenElement=document.getElementsByName(“\uu-RequestVerificationToken”)[0];
风险值数据={
__RequestVerificationToken:tokenElement.value
}
$.ajax({
类型:“POST”,
url:uri,
数据:数据,
成功:功能(结果){
成功(结果);
}
});
}
返回false;
}
功能成功(结果){
$(“#时间表”).html(结果);
}

页面只呈现html,javascript处理实际的Ajax帖子。我认为您缺少的是请求中的验证令牌。

这是因为您实际上没有发布表单。请将其正确传递并在ajax数据列表中添加
\u令牌
,该令牌的值将来自
@Html.AntiforgeryToken()
尝试一下,它可以解决路由错误(不同的url操作)以及控制器上的参数: JavaScript

<script type="text/javascript">
function DeleteSchedule(id) {
    if (confirm('Are you sure you want to delete this Schedule?')) {
        $.ajax({
            type: "POST",
            url: '@Url.Action("Delete", "Schedule")',
            data: "id=" + id ,
            async: true,
            cache: false,
            success: function (result) { success(result); }
        });
    }
    return false;
}

function success(result) {
    $("#ScheduleList").html(result);
}
</script>

Nicola.

Hi,为什么您有
contentType:“application/json”
?因为在你的服务器端你得到int?能否将
{id}
更改为
JSON.stringify({'id':id})
,然后重试?请提供详细信息,解释解决方案解决原始问题的原因和方式
data: { 
'id': id,
'__RequestVerificationToken': $('[name="__RequestVerificationToken"]').val()
}
<script type="text/javascript">
function DeleteSchedule(id) {
    if (confirm('Are you sure you want to delete this Schedule?')) {
        $.ajax({
            type: "POST",
            url: '@Url.Action("Delete", "Schedule")',
            data: "id=" + id ,
            async: true,
            cache: false,
            success: function (result) { success(result); }
        });
    }
    return false;
}

function success(result) {
    $("#ScheduleList").html(result);
}
</script>
 [HttpPost]
 [ValidateAntiForgeryToken]
   public ActionResult Delete(string id)
    {
      //do stuff
    }