0

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
BigBadDom
  • 219
  • 1
  • 8
  • 17

3 Answers3

4

I think this should work:

$.post("Home/PostExample", { myString: $("#exampleCssId").val() } );
Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
grega g
  • 1,079
  • 1
  • 12
  • 25
1

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);
}
Tridus
  • 5,021
  • 1
  • 19
  • 19
1

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);    
});
Bhaskar
  • 1,680
  • 7
  • 26
  • 40