admin管理员组

文章数量:1406328

I'm using jQuery to post back to my controller, but i'm wondering how you pass values as parameters in the ActionResult. For example:

I have a jQuery post:

$.post("Home\PostExample")

but i would like to include a value from a dropdown menu:

@Html.DropDownListFor(m => m.Example, Model.Example, new { @id = "exampleCssId" })

into an Actionresult:

[HttpPost]
public ActionResult PostExample(string myString)
{
    //TODO: Write contents of ActionResult
}

Any help would be appreciated.

Thanks.

I'm using jQuery to post back to my controller, but i'm wondering how you pass values as parameters in the ActionResult. For example:

I have a jQuery post:

$.post("Home\PostExample")

but i would like to include a value from a dropdown menu:

@Html.DropDownListFor(m => m.Example, Model.Example, new { @id = "exampleCssId" })

into an Actionresult:

[HttpPost]
public ActionResult PostExample(string myString)
{
    //TODO: Write contents of ActionResult
}

Any help would be appreciated.

Thanks.

Share Improve this question edited Jun 2, 2011 at 12:28 abatishchev 100k88 gold badges301 silver badges442 bronze badges asked Jun 2, 2011 at 12:09 BigBadDomBigBadDom 2191 gold badge8 silver badges17 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

I think this should work:

$.post("Home/PostExample", { myString: $("#exampleCssId").val() } );

Here's an example from something I did recently:

function SaveNewGoal() {
    var data = { Name_E: $("#NewGoal #Name_E").val(),
        Name_F: $("#NewGoal #Name_F").val(),
        Desc_E: $("#NewGoal #Desc_E").val(),
        Desc_F: $("#NewGoal #Desc_F").val()
    };

    $.ajax({
        url: '@Url.Action("CreateJson", "Goal")',
        data: JSON.stringify(data),
        success: SaveNewGoalSuccess,
        error: SaveNewGoalError,
        cache: false,
        type: 'POST',
        contentType: 'application/json, charset=utf-8',
        dataType: 'json'
    });
}

function SaveNewGoalSuccess(data, textStatus, jqXHR) {
    $("#NewGoalContainer").hide();
    // reload the goal list
    ReloadGoals();
}

function SaveNewGoalError(jqXHR, textStatus, errorThrown) {
    $("#NewGoalResult").text("Error: " + jqXHR.responseText);
}

Adding to grega's answer, you can also make use of callback function if you want to return some data from action method and display it to user.

 $.post("Home/PostExample", { myString: $("#exampleCssId").val() }, function(result){    
     alert(result);    
});

本文标签: cUsing jQuery to post back to a controllerStack Overflow