BigBadDom
BigBadDom

Reputation: 219

Using jQuery to post back to a controller

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.

Upvotes: 0

Views: 4893

Answers (3)

Bhaskar
Bhaskar

Reputation: 1690

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

Upvotes: 1

Tridus
Tridus

Reputation: 5081

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

Upvotes: 1

grega g
grega g

Reputation: 1089

I think this should work:

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

Upvotes: 4

Related Questions