Ajax.ActionLink post entire model from a view?

asp.net-mvc asp.net-mvc-3 c# entity-framework razor

Question

I have a view that is strongly typed to a ViewModel. Is it possible to pass all of the data from a model in the view, back to a controller action? Something like this?

@Ajax.ActionLink("(Export to Excel)", "ExportCsv", "SurveyResponse", new {  
ResultsViewModel = Model }, new AjaxOptions {HttpMethod = "POST"})

And then collect the data from ResultsViewModel as a parameter in another controller

public ActionResult ExportCsv(ResultsViewModel resultsviewmodel)
{

}
1
7
10/10/2012 11:49:52 PM

Popular Answer

No, you cannot pass entire view model like this in an action link. You could pass only the id of this model and then retrieve the actual model using this id from wherever you retrieved it initially:

@Ajax.ActionLink(
    "(Export to Excel)", 
    "ExportCsv", 
    "SurveyResponse", 
    new { id = Model.Id }, 
    new AjaxOptions { HttpMethod = "POST" }
)

As an alternative you could serialize the model as a javascript literal and then send it as a JSON data with the AJAX request:

@Html.ActionLink(
    "(Export to Excel)", 
    "ExportCsv", 
    "SurveyResponse", 
    null, 
    new { @class = "exportCsv" }
)
<script type="text/javascript">
    $('.exportCsv').click(function() {
        var model = @Html.Raw(Json.Encode(Model));
        $.ajax({
            url: this.href,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function(result) {

            }
        });
        return false;
    });
</script>
4
10/11/2012 6:39:20 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow