简体   繁体   English

使用ajax将值传递给控制器

[英]pass value to controller by using ajax

I want to pass value from view to controller by using ajax. 我想通过使用ajax将值从视图传递给控制器​​。

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

My script: 我的剧本:

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

        data: {
            choiceId: "1"
        }


});
}

Controller: 控制器:

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

but choiceId always null 但是choiceId总是为空

Change couple of things. 改变一些事情。

First assign an id or class to your button.Second remove inline onclick function and use ajax click function.Then specify the request type as Post. 首先为您的按钮分配一个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');
        }
    });
});

Then your controller should look like this 然后你的控制器应该是这样的

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

I don't know how you are populating your viewmodel,so I purposely removed them and shown an working example. 我不知道你是如何填充你的viewmodel,所以我故意删除它们并显示一个工作示例。

In case you want to pass viewmodel you should construct your data object like this: 如果你想传递viewmodel,你应该像这样构建你的数据对象:

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

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

Sample structure of SurveyViewModel I assume: SurveyViewModel的示例结构我假设:

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

Since there are two parameter in your controller, you need to identify them both form the client side. 由于控制器中有两个参数,因此您需要从客户端识别它们。 Further, you should specify the contentType . 此外,您应指定contentType

You spread the payload like so: 你像这样传播有效载荷:

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'
    }
});
}

You can also pass like this 你也可以像这样通过

or for more parameters 或更多参数

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