Ajax.ActionLink post entire model from a view?
Solution 1
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>
Solution 2
Managed to make below works,
@Ajax.ActionLink("(Export to Excel)", "ExportCsv", "SurveyResponse",
new { Model.F1, Model.F2, Model.OtherFields }, new AjaxOptions {HttpMethod = "POST"})
Controller
[HttpPost]
public ActionResult ExportCsv(ResultsViewModel resultsviewmodel)
{
}
This is a http post, but the data in not in "form data", it's encoded in request's URL (but not a http get).
Looks like MVC automatically converts the individual fields into a single model.
URL has a length limits, large model may fail.
user547794
Updated on June 19, 2022Comments
-
user547794 almost 2 years
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) { }
-
Zapnologica almost 8 yearsWhy do you have
[HttpGet]
in controller and thenHttpMethod = "POST"
in the view?