简体   繁体   中英

pass value to controller by using ajax

I want to pass value from view to controller by using 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

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.

$('#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.

In case you want to pass viewmodel you should construct your data object like this:

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

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

Sample structure of SurveyViewModel I assume:

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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