繁体   English   中英

使用ajax将值传递给控制器

[英]pass value to controller by using ajax

我想通过使用ajax将值从视图传递给控制器​​。

 <button onclick="addCommentByAjax()" >Save</button>

我的剧本:

function addCommentByAjax() {
    $.ajax({
        type: "POST",
        url: '/Survey/DoDetailSurvey',

        data: {
            choiceId: "1"
        }


});
}

控制器:

 [HttpPost]
    public ActionResult DoDetailSurvey(SurveyViewModel model, string choiceId)
    {
     //
    }

但是choiceId总是为空

改变一些事情。

首先为您的按钮分配一个id或类。第二个删除内联onclick函数并使用ajax click函数。 click将请求类型指定为Post。

$('#btnComment').click(function () {       
    var choiceId = $('#YourChoiceId').val();

    $.ajax({
        url: '/Survey/DoDetailSurvey',
        data: { 'choiceId' : choiceId},
        type: "post",
        cache: false,
        success: function (response) {
           //do something with response
        },
        error: function (xhr, ajaxOptions, thrownError) {
             alert('error occured');
        }
    });
});

然后你的控制器应该是这样的

[HttpPost]
public ActionResult DoDetailSurvey(string choiceId)
{
     //
}

我不知道你是如何填充你的viewmodel,所以我故意删除它们并显示一个工作示例。

如果你想传递viewmodel,你应该像这样构建你的数据对象:

var data = {};
data.Property1 = some val;
data.Property2 = "some val";   

$.post('/Survey/DoDetailSurvey', data);

SurveyViewModel的示例结构我假设:

public class SurveyViewModel 
{
    public int Property1 { get; set; }
    public string Property2 { get; set; }
}

由于控制器中有两个参数,因此您需要从客户端识别它们。 此外,您应指定contentType

你像这样传播有效载荷:

function addCommentByAjax() {
    var payload =  {
        model: {
        // whatever properties you might have
        },
        choiceId: 1
    };

    $.ajax({
        type: "POST",
        url: '/Survey/DoDetailSurvey',
        contentType: 'application/json',
        data: JSON.stringify(payLoad)
    });
}
function addCommentByAjax() {
$.ajax({
    type: "POST",
    url: '/Survey/DoDetailSurvey?choiceId=1'
    }
});
}

你也可以像这样通过

或更多参数

function addCommentByAjax() {
$.ajax({
    type: "POST",
    url: '/Survey/DoDetailSurvey?choiceId=1&Name=Arun'
    }
});
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM